php OOP 父子关系
class base{
public $c = 'c';
public $sub = '';
function __construct(){
$this->sub = new sub();
}
}
class sub extends base{
public $ab = 'abs';
function __construct(){
$this->c = 'aas';
echo 'Test';
}
}
$a = new base();
print_r($a);
我想让子类编辑基本变量 $this->c = 'blabla';
我怎样才能实现这一点?
class base{
public $c = 'c';
public $sub = '';
function __construct(){
$this->sub = new sub();
}
}
class sub extends base{
public $ab = 'abs';
function __construct(){
$this->c = 'aas';
echo 'Test';
}
}
$a = new base();
print_r($a);
I would like to the sub class to edit the base vars $this->c = 'blabla';
how can i achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不直接覆盖它:
否则,如果您需要修改实际的基本属性,请按照 Wrikken 的建议使用
parent
。Why not just override it:
Otherwise, if you need to modify the actual base property, use
parent
as Wrikken suggested.这不会是我引以为傲的代码(不同的构造函数签名),但这会起作用(单次使用):
如果您更频繁地需要它:
根据实际需求,另一种设计模式可能更适合。
't wouldn't be code I was proud of (different constructor signatures), but this would work (single use):
If you need it more often:
Depending on what the actual needs are, another design pattern is likely more suited.