简体   繁体   English

Laravel类命名空间

[英]Laravel Class Namespacing

I have created a few custom classes in App/ of laravel 5 as such: 我在laravel 5的App /中创建了一些自定义类,如下所示:

App/Database.php 应用/ database.php中
App/Table.php 应用/ Table.php
App/ContactsTable.php 应用/ ContactsTable.php

In my ContactsTable class, I'm extending the Table class 在我的ContactsTable类中,我扩展了Table类

use Table;
/**
 * Description of ContactsTable
 * 
 * @author john
 */
class ContactsTable extends Table {

I have the aliases setup in config/app.php for Table (App\\Table) and ContactsTable (App\\ContactsTable). 我在config / app.php中为表(App \\ Table)和ContactsTable(App \\ ContactsTable)设置了别名。 But when loading the page it gives me an error: 但是在加载页面时,它给了我一个错误:

"The use statement with non-compound name 'Table' has no effect" “具有非化合物名称'Table'的use语句无效”

I have tried multiple combinations of importing the class in different ways, with no luck. 我尝试过多种组合,以不同的方式导入该类,但是没有运气。

Any advice? 有什么建议吗?

It's because you are currently in the same namespace as the Table class. 这是因为您当前与Table类位于同一命名空间中。 Since you also aliased it as Table , it probably doesn't know what Table you are talking about, the aliased one which is Table or the Table that currently resides in your current namespace, which both happen to also be the same thing. 由于您也将其别名为Table ,因此它可能不知道您在说什么Table ,别名是Table或当前位于当前名称空间中的Table ,这两者碰巧也是一样。

Remove the alias and remove the use statement. 删除别名并删除use语句。 Since these classes are in the same namespace, there is no need to do either of those things. 由于这些类位于同一名称空间中,因此无需执行任何一项操作。

It's also likely a very good idea to keep both un-aliased and in the App namespace because those are both pretty common names and might end up causing you more trouble in the future. 避免混叠和保留在App命名空间中也是一个好主意,因为它们都是很普通的名称,将来可能会给您带来更多麻烦。

I just tried to recreate this and everything works fine here. 我只是试图重新创建它,并且在这里一切正常。 Just to be sure though, here is the code I used... 只是为了确定,这是我使用的代码...

app\\ContactsTable.php 应用程序\\ ContactsTable.php

namespace App;

class ContactsTable extends Table {

}

app\\Table.php 应用程序\\ Table.php

namespace App;

class Table {

}

routes.php routes.php文件

Route::get('test', function()
{
    $table = new \App\ContactsTable();

    echo get_class($table);
});

And going to myapp.local/test , it outputs App\\ContactsTable 然后转到myapp.local/test ,它输出App\\ContactsTable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM