php继承:子类继承父类中的数据


php inheritance: children classes to inherit the data in the parent class?

有时我会迷失方向,开始怀疑我在php中编写类是否做得正确。

例如,这些都是非常基本和简单的类,

class base {
    protected $connection = null;
    /**
     * Set the contructor for receiving data.
     */
    public function __construct($connection)
    {
        $this->connection = $connection;
    }
    public function method()
    {
        print_r(get_object_vars($this));
    }
}
class child extends base{
    public function __construct(){
    }
    public function method()
    {
        print_r(get_object_vars($this));
    }
}

我有从base扩展而来的child类。并且我将一些数据/信息传递到base类中。我希望child类继承我刚才传递的数据/信息。例如,

$base = new base("hello");
$child = new child(); 
$child->method(); 

所以我假设我得到Array ( [connection] => hello )作为我的答案。

但我得到的实际上是Array ( [connection] => )

因此,这意味着我每次都必须将这段数据传递到从基础扩展的子类中。否则我不会得到Array ( [connection] => hello )作为我的答案。

是否有正确的方法编写子类以继承父类传递的数据?

您似乎以某种方式混淆了模板(类)和对象(类的实例)。

  • 用一些给定的初始值实例化base类的一个对象会对child类的其他对象产生什么影响?类child实例不会动态"继承"类base实例

  • 如果您想从base__construct方法初始化一些受保护的属性,并且如果您想在不必重写__construct方法的情况下也从child类初始化这些属性,那么您必须不覆盖child类的__construct方法。