【发布时间】:2023-03-27 03:30:01
【问题描述】:
有时我会迷路并开始怀疑我是否在用 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 ) 作为我的答案。
有没有正确的方法编写子类来继承父类传递的数据?
【问题讨论】:
-
为什么不在构造函数中分配'hello',然后一切都设置好了......这两个实例化的类之间没有连接,以便孩子可以继承'hellp'
-
对不起,我不明白。你能给我举个例子吗?谢谢。
-
哇。忽略它。我现在明白了。
-
我的问题是数据必须从外部传递。不能在父类中设置。
标签: php oop inheritance php-5.4