-1
为什么我在尝试调用不相关的构造函数时遇到错误?从另一个类中调用的构造返回致命错误
Fatal error: Non-static method Employee::__construct() cannot be called statically, assuming $this from incompatible context in..
为什么我在尝试调用不相关的构造函数时遇到错误?从另一个类中调用的构造返回致命错误
Fatal error: Non-static method Employee::__construct() cannot be called statically, assuming $this from incompatible context in..
你需要使用它像往常一样构造函数来实例化无关类:
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
错误工作正常。像这样的: -
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());
不过不要担心太多很多,如果你现在还不明白。
你只需要调用这个类,这个构造会被自动触发,即''employee = new Employee();' – cmorrissey
不要使用类的名字,而应该使用关键字'parent :: __ construct()' 。 –
@watcher它不是父母... – cmorrissey