php继承:子类继承父类中的数据?
有时我迷路了,开始怀疑我用php编写类是否正确 比如说,这些都是非常基本和简单的类php继承:子类继承父类中的数据?,php,oop,inheritance,php-5.4,Php,Oop,Inheritance,Php 5.4,有时我迷路了,开始怀疑我用php编写类是否正确 比如说,这些都是非常基本和简单的类 class base { protected $connection = null; /** * Set the contructor for receiving data. */ public function __construct($connection) { $this->connection = $connection;
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
类中。我希望子类继承我刚才传递的数据/信息。比如说,
$base = new base("hello");
$child = new child();
$child->method();
所以我假设我得到数组([connection]=>hello)
作为我的答案
但是我得到了这个数组([connection]=>)
这意味着我每次都必须将这段数据传递到子类中,该类从基础扩展而来。否则我就不会得到数组([connection]=>hello)
作为我的答案
有没有正确的方法来编写子类来继承从父类传递的数据?似乎您在某种程度上混淆了模板(类)和对象(类的实例)
- 用一些给定的初始值实例化类
base
的一个对象对类child
的其他对象有什么影响?
类子类的实例将不会动态“继承”类基类的实例的某些属性
- 如果您想从
基本类构造方法初始化一些受保护的属性,并且如果您想从子类方法初始化这些属性,而不必重新编写构造方法,然后,您不能覆盖您的子类的构造方法
为什么不在构造函数中分配“hello”,例如,然后设置所有内容……这两个实例化的类之间没有连接,因此子类可以继承“hellp”对不起,我不明白。你能给我举个例子吗?谢谢。别理它。我现在明白了。我的问题是数据必须从外部传递。无法在父类中设置。感谢您的回复。如何不覆盖子类的u构造方法。
?