当第一个类被实例化时,是否可以实例化第二个类而不使用构造函数?


Is it possible to instantiate a second class when the first gets instantiated without using a constructor?

很抱歉,标题措辞不当。我不太了解面向对象的PHP,所以,我想不出一个更好的标题(或对我的问题的答案!)。

好的,我有这样的东西:

Class foo{
    var $hello;
    function foo(){
    }
}
Class customfoo extends foo{
    //No Constructor
}

现在,我写了另一个类,我们叫它customclass,我想在customfoo类中使用它。但是,我不只是想在customfoo类中使用它,我想在customfoo类创建时立即创建它。

通常情况下,我认为,您只会使用this的构造函数,所以类似于:

 Class customfoo extends foo{
    var $custom;
    function customfoo(){
        $this->custom = new customclass();   
    }
}

然而,customfoo是一个子类,所以,我认为构造函数会取代父类的构造函数,我不希望这种情况发生。那么,当customfoo首次启动时,我如何创建customclass类呢?我想,我可以只是写一个任意的函数,并通过其他函数调用它(我肯定会在早期执行),但它会很好,至少知道如何做到以上。

首先,您应该将您的构造函数命名为__construct

正如您所指出的,您编写的构造函数将覆盖父类的构造函数,但您始终可以从子类调用它,如下所示:

Class customfoo extends foo{
    var $custom;
    function __construct(){
        parent::__construct();
        $this->custom = new customclass();
    }
}