请参阅以下示例(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
}
}
Run Code Online (Sandbox Code Playgroud)
我是OOP的新手并且有点无知.
这里访问parent属性我正在使用该类的一个实例,这似乎是错误的:S(不需要我是孩子).有没有一种简单的方法,以便我可以将父属性与子属性同步,并且可以直接访问$ this-> anotherP而无需使用$ this-> parent-> anotherP?
Pas*_*TIN 30
当你的Child类扩展您的Parent课,每次要么是属性和方法public或protected在Parent类将由可以看出Child,好像他们是在定义的类Child和角落找寻另一种方式-类.
当Child类extends是Parent类时,它可以被视为" Child是一个Parent" - 这意味着它Child具有属性Parent,除非它重新定义了另一种方式.
(顺便说一句,请注意" parent"是一个保留的关键字,在PHP中 - 这意味着你不能用该名称命名一个类)
这是"父"类的快速示例:
class MyParent {
protected $data;
public function __construct() {
$this->someMethodInTheParentClass();
}
protected function someMethodInTheParentClass() {
$this->data = 123456;
}
}
Run Code Online (Sandbox Code Playgroud)
它是"孩子"类:
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
}
}
Run Code Online (Sandbox Code Playgroud)
这可以这样使用:
$a = new Child();
var_dump($a->getData());
Run Code Online (Sandbox Code Playgroud)
你会得到输出:
int 123456
Run Code Online (Sandbox Code Playgroud)
这意味着$data在MyParent类中定义并在同一MyParent类的方法中初始化的属性可由Child类访问,就像它自己的类一样.
为了简单起见:因为Child"是一个" MyParent,它不需要保持指向...本身;-)