从父范围访问子属性 [英] Access child property from parent scope
本文介绍了从父范围访问子属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个父类来访问其子属性:
I need a parent class to access its child properties:
class Parent {
private $_fields = null;
public function do_something() {
// Access $_fields and $child_var here
}
}
class Child extends Parent {
private $child_var = 'hello';
}
$child = new Child();
$child->do_something();
从子作用域修改$_fields
时,它仍在父作用域中null
.当尝试使用$this->child_var
从父范围访问$ child_var时,它当然是未定义的.
When $_fields
is modified from the child scope, it's still null
in the parent scope. When trying to access $child_var from parent scope using $this->child_var
, it's of course undefined.
我没有找到像功能集"这样的东西会被复制到子类中.
I didn't find anything like a "function set" that would just be copied in the child class...
推荐答案
看看有关可见性.
基本上,您不能访问父级的private
属性/方法,父级也不能访问其子级的属性/方法.但是,您可以改为声明您的属性/方法protected
.
Basically, you cannot access parent's private
properties/methods nor can the parent access its child's. However, you can declare your property/method protected
instead.
class Parent {
protected $_fields = null;
public function do_something() {
// Access $_fields and $child_var here
}
}
class Child extends Parent {
protected $child_var = 'hello';
}
$child = new Child();
$child->do_something();
这篇关于从父范围访问子属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文