2015-12-10 52 views
1

我有一个名为Service_B的类,它扩展了自定义服务类。如何在父类构造函数中使用名称空间

此自定义服务类需要在其__construct()中命名为Reader的单个对象才能正确实例化。

父服务被定义为跟随

namespace Vendor\Services; 

abstract class Service{ 

    function __construct(Vendor\Services\Reader $reader){ 
    } 
} 

Service_B定义如下:

namespace Vendor\Services;  

class Service_B extends Service{ 

    function __construct(){ 
     parent::__construct(new \Vendor\Services\Reader()); 
    } 
} 

Reader确实有在文件的顶部以下行:

use Vendor\Services; 

类文件的结构如下:

Vendor/Services/Service_B.php 
Vendor/Services/Reader.php 

问题: 当我实例SERVICE_B,我收到以下错误信息:

Fatal error: Class 'Vendor\Services\Reader' not found 

我不明白为什么,因为我想我使用了正确的命名空间我得到这个错误声明。谢谢

回答

3

在您Reader类地方的顶部:

//This will declare the Reader class in this namespace 
namespace Vendor\Services; 

,并删除:

//THIS IS A WRONG DIRECTIVE: you're telling PHP to use the Vendor\Services class but it doesn't even exist  
use Vendor\Services; 

然后修改Service_B类如下:

namespace Vendor\Services;  

//i think this should extend Service, as it's calling the parent constructor 
class Service_B extends Service 
{ 
    function __construct(){ 
     parent::__construct(new Reader()); 
    } 
} 

这样,所有你的3个类将位于相同的命名空间中,并且该Reader类应该没有明确的命名空间前缀

+0

是Service_B扩展服务我已经编辑了相应的原始文章 – Vincent

+1

谢谢,用'namespace'替换'use'解决了这个问题。 – Vincent

相关问题