从孩子访问父类的属性 [英] Accessing Parent Class' property from child
问题描述
请参见以下示例(PHP)
See the following example (PHP)
class Parent
{
protected $_property;
protected $_anotherP;
public function __construct($var)
{
$this->_property = $var;
$this->someMethod(); #Sets $_anotherP
}
protected function someMethod()
...
}
class Child extends Parent
{
protected $parent;
public function __construct($parent)
{
$this->parent = $parent;
}
private function myMethod()
{
return $this->parent->_anotherP; #Note this line
}
}
我是OOP的新手,有点无知.
I am new to OOP and am a bit ignorant.
这里我使用的是该类的实例来访问parents属性,这似乎是错误的:S(然后不需要成为i的孩子).有没有一种简单的方法,这样我就可以将父属性与子属性同步,并且可以直接访问$ this-> otherotherP,而不必使用$ this-> parent-> anotherP吗?
Here to access the parents property I am using an instance of that class, which seems wrong :S (no need of being i child then). Is there an easy way, so that i can sync the parent properties with the child properties and can directly access $this->anotherP without having to use $this->parent->anotherP ?
推荐答案
随着您的Child
类扩展Parent
类,Parent
中public
或protected
的每个属性和方法Child
类将看到该类,就像它们是在Child
类中定义的一样-反之亦然.
As your Child
class is extending your Parent
class, every properties and methods that are either public
or protected
in the Parent
class will be seen by the Child
class as if they were defined in the Child
class -- and the other way arround.
当Child
类extends
Parent
类时,可以将其视为"Child
是Parent
" -这表示Child
具有Parent
的属性,除非它以另一种方式重新定义了它们.
When the Child
class extends
the Parent
class, it can be seen as "Child
is a Parent
" -- which means the Child
has the properties of the Parent
, unless it redefines those another way.
(顺便说一句,请注意,"parent
"是PHP中的保留关键字,这意味着您不能使用该名称来命名一个类)
(BTW, note that "parent
" is a reserved keyword, in PHP -- which means you can't name a class with that name)
这是父"类的简单示例:
Here's a quick example of a "parent" class :
class MyParent {
protected $data;
public function __construct() {
$this->someMethodInTheParentClass();
}
protected function someMethodInTheParentClass() {
$this->data = 123456;
}
}
这是子"类:
class Child extends MyParent {
public function __construct() {
parent::__construct();
}
public function getData() {
return $this->data; // will return the $data property
// that's defined in the MyParent class
}
}
可以通过这种方式使用:
That can be used this way :
$a = new Child();
var_dump($a->getData());
然后您将得到输出:
int 123456
这意味着$data
属性是在MyParent
类中定义的,并且是在同一MyParent
类的方法中初始化的,因此Child
类可以访问它,就像它是自己的一样.
Which means the $data
property, defined in the MyParent
class, and initialized in a method of that same MyParent
class, is accessible by the Child
class as if it were its own.
为了简单起见:由于Child
是" MyParent
,它不需要保持指向...本身的指针;-)
To make things simple : as the Child
"is a" MyParent
, it doesn't need to keep a pointer to... itself ;-)
这篇关于从孩子访问父类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!