【问题标题】:php inheritance: children classes to inherit the data in the parent class?php继承:子类继承父类中的数据?
【发布时间】: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


【解决方案1】:

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

  • 用一些给定的初始值实例化一个 base 类的对象对 child 类的其他对象有何影响? child 类的实例 不会动态“继承”base 类的实例 的某些属性。

  • 1234563方法,那么你不能覆盖 child 类的 __construct 方法。

【讨论】:

  • 感谢您的回复。我怎么NOT overwrite the __construct method of your child class.?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-11
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多