有时我会迷失方向,开始怀疑我在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
方法。