Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在父类构造函数中使用命名空间_Php_Oop_Namespaces - Fatal编程技术网

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

Php 如何在父类构造函数中使用命名空间,php,oop,namespaces,Php,Oop,Namespaces,我有一个名为Service_B的类,它扩展了一个定制服务类 此自定义服务类需要在其\uuu构造()中有一个名为Reader的对象才能正确实例化 父服务的定义如下 namespace Vendor\Services; abstract class Service{ function __construct(Vendor\Services\Reader $reader){ } } 服务定义如下: namespace Vendor\Services; class Ser

我有一个名为
Service_B
的类,它扩展了一个定制服务类

此自定义服务类需要在其
\uuu构造()
中有一个名为
Reader
的对象才能正确实例化

父服务的定义如下

namespace Vendor\Services;

abstract class Service{

    function __construct(Vendor\Services\Reader $reader){
    }
}
服务定义如下:

namespace Vendor\Services;    

class Service_B extends Service{

    function __construct(){
        parent::__construct(new \Vendor\Services\Reader());
    }
}
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() );
    }
}
读卡器
文件顶部有以下行:

use Vendor\Services;
类文件的组织方式如下:

Vendor/Services/Service_B.php
Vendor/Services/Reader.php
问题: 当我实例化服务_B时,我得到以下错误消息:

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

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

在您的
读者
课堂上:

//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;
然后修改
服务\u B
类,如下所示:

namespace Vendor\Services;    

class Service_B extends Service{

    function __construct(){
        parent::__construct(new \Vendor\Services\Reader());
    }
}
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
类应该没有明确的名称空间前缀

Yes Service\u B extensed Service我已经按照原帖编辑了谢谢,将“use”替换为“namespace”修复了问题。