在非层次结构中从另一个类调用的构造返回致命错误

时间:2014-05-15 20:13:53

标签: php oop

为什么在尝试调用不相关的构造函数时出错?

class Employee
{
    function __construct() 
    {
        echo "<p>Employee construct called!!</p>";
    }
}

class Manager
{
    function __construct()
    {
        Employee::__construct();
        echo "<p> Manager Construct Called! </p>";
    }
}

在子类中调用它时工作正常

class Manager extends Employee

错误:

Fatal error: Non-static method Employee::__construct() cannot be called statically, assuming $this from incompatible context in..

1 个答案:

答案 0 :(得分:0)

您需要像往常一样使用其构造函数实例化不相关的类。像这样: -

class Employee
{
    function __construct() 
    {
        echo "<p>Employee construct called!!</p>\n";
    }
}

class Manager
{

    protected $employee;

    function __construct()
    {
        $this->employee = new Employee();
        echo "<p>Manager Construct Called! </p>\n";
    }
}

new Manager();

这是一种简单的方法,但将员工作为依赖项传递给构造函数是更好的做法: -

class Employee
{
    function __construct() 
    {
        echo "<p>Employee construct called!!</p>\n";
    }
}

class Manager
{

    protected $employee;

    function __construct(Employee $employee)
    {
        $this->employee = $employee;
        echo "<p>Manager Construct Called! </p>\n";
    }
}

$manager = new Manager(new Employee());

但如果你现在不明白,不要太担心。

See it working