如何在父类构造函数

时间:2015-12-10 14:44:43

标签: php oop namespaces

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

此自定义服务类在其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

我不明白为什么我会收到此错误,因为我认为我正在使用正确的命名空间声明。谢谢

1 个答案:

答案 0 :(得分: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类而没有显式名称空间前缀