【发布时间】:2017-04-10 17:29:58
【问题描述】:
我有一组包含类(实体)的 PHP 文件。每个类都有相同的命名空间:
// src/App/Entity/Actions.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Actions
*
* @ORM\Entity
*/
class Actions
{
// SOME CODE
我使用 composer 自动加载包含类的 PHP 文件:
"autoload": { "psr-0": { "App": "src/" } }
在我的 bootstrap.php 文件中,我添加了这一行:
use App\Entity;
所以我想因为告诉应用程序使用 App\Entity 命名空间,我可以像这样调用实体类:$entity = new Actions();
但是当我尝试这样做时,我得到了这个错误:
致命错误:第 49 行的 C:\wamp64\www\spider\chebi2\inc\orm_tools.php 中找不到类“操作”
如果我这样做:
use App\Entity; use App\Repository;
if (class_exists('Actions')) { dump('exists'); } else { dump('not exists'); }
if (class_exists('\App\Entity\Actions')) { dump('exists'); } else { dump('not exists'); }
这是它的输出:
PS C:\wamp64\www\spider\chebi2> php .\get_actions.php
"not exists"
"exists"
所以它只有在我提供完整的命名空间时才能找到该类。奇怪的是,当我尝试这个时:
// Direct path to the Actions.php file
use App\Entity\Actions;
if (class_exists('Actions')) { dump('exists'); }
else { dump('not exists'); }
if (class_exists('\App\Entity\Actions')) { dump('exists'); }
else { dump('not exists'); }
我得到相同的结果:
PS C:\wamp64\www\spider\chebi2> php .\get_actions.php
"not exists"
"exists"
所以现在我更加困惑了。使用use App\Entity; 的意义何在?如果它实际上并没有使该命名空间中的类直接可用?为什么将直接路径分配给use App\Entity\Actions; 类甚至不起作用?
我在这里做错了吗?有没有正确的方法来使用我不理解的命名空间?
【问题讨论】:
标签: php namespaces psr-0