如何在父类构造函数中使用命名空间


How to use namespace in a parent class constructor

我有一个名为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

我不明白为什么会出现这个错误,因为我认为我使用了正确的名称空间声明。感谢

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类应该在没有显式命名空间前缀

的情况下找到