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

标签 php oop namespaces

我有一个名为 Service_B 的类(class)它扩展了自定义服务类。

这个自定义服务类需要一个名为 Reader 的对象。在其 __construct()以便正确实例化。

父服务定义如下

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应该在没有显式命名空间前缀的情况下找到类

关于php - 如何在父类构造函数中使用命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34204795/

相关文章:

php - mkdir() : Permission denied

php - 这是一个 php 错误 : subclasses must declare private methods with the same signature as in parent class

找不到 PHP 命名空间类

python - 脚本之间的全局变量

java - 用模式替换 if else 语句

xml - 如何在 XML 中定义命名空间?

php - 您什么时候准备好使用 PHP 框架?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - 将另一个查询放在 mysql 和 php 的 where 子句中

perl - 将 Perl 对象的类更改为子类