PHP继承和设置父构造中的变量


PHP Inheritance and setting variables in parent constuct

嗨,我想知道是否有人能为我解释以下问题。

我有两个班

1级

class application{
    private $something = "hello my name is";
    function __construct(){
       $this->something .= " bob";
       $this->require_login_class_method();
    }
    public function getName(){
        return $this->something;
    }
    ...
}

2级

class login extends application{
    function __construct(){
       echo $this->getName();
    }
}

我的结果总是

"我的名字是"

"bob"

但是,如果我调用(在类登录构造中)

parent::__construct();

它是有效的。

如果我的应用程序类构造方法接受了我不想传递或不必第二次传递的变量(从登录开始),该怎么办?

提前感谢


解决方案

感谢所有作出回应的人。

到目前为止,我收集的解决方案是进行以下

类应用

//if variables are present, make them optional
function __construct($var1 = null, $var2 = null){
    //do something
}

类登录

function __construct(){
    parent::__construct();
    //do something with variables set in parent construct
}

如果扩展类,则可以覆盖构造函数。如果你这样做了,你必须为自己做在构造函数中完成的所有工作。您也可以调用父构造函数,并调用那里完成的所有工作。实际上没有第三种选择:要么你叫它,要么你不叫它。

我认为严格的标准要求您的子构造函数接受与其父构造函数相同的变量,但如果您想绕过这一点,您可以始终在父构造函数中使变量可选:

function __construct($name = " bob"){
   $this->something .= $name;
   $this->require_login_class_method();
}

当然,如果你重写构造函数,如果你想调用它,就必须从子级手动调用它。

在OO中,您可以覆盖方法。因此,您覆盖了父类(意味着在调用子类时不会执行它)
您可以调用任何父方法parent::anyMethod()

这就是它的工作原理。

必须使用未设置默认值的每个参数来调用父级-__constructor。如果你不想设置某些变量,你必须在你的父构造函数中设置默认值,或者重新实现整个代码。

您可以在构造函数中设置变量。所以你需要先打电话。例如:

class login extends application{
    function __construct(){
       parent::__construct();
       echo $this->getName();
    }
}

如果需要传递变量,则必须手动执行:

class login extends application{
    function __construct($x){
       parent::__construct($x);
       echo $this->getName();
    }
}

是的,这有点像离合器。如果可以的话,尽量不要重写构造函数。此外,尽量避免在构造函数中执行任何繁重的逻辑(如登录远程服务)。最好以后再按要求做。