我尝试从其扩展子项访问父项的属性,类似于下面的概念,
class Base
{
protected static $me;
protected static $var_parent_1;
protected static $var_parent_2;
public function __construct ($var_parent_1 = null)
{
$this->var_parent_1 = $var_parent_1;
$this->me = 'the base';
}
public function who() {
echo $this->me;
}
public function parent_1() {
echo $this->var_parent_1;
}
}
class Child extends Base
{
protected static $me;
protected static $var_child_1;
protected static $var_child_2;
public function __construct ($var_child_1 = null)
{
parent::__construct();
$this->var_child_1 = $var_child_1;
$this->me = 'the child extends '.parent::$me;
}
// until PHP 5.3, will need to redeclare this
public function who() {
echo $this->me;
}
public function child_1() {
echo $this->var_child_1;
}
}
$objA = new Base($var_parent_1 = 'parent var 1');
$objA->parent_1(); // "parent var 1"
$objA->who(); // "the base"
$objB = new Child($var_child_1 = 'child var 1');
$objB->child_1(); // "child var 1"
$objB->who(); // should get "the child extends the base"
但我得“孩子延伸”而不是“孩子扩展基础”如果我使用$this->
如果我将所有$this->
更改为self::
为什么?
这是访问父级属性的唯一正确方法,即将所有$this->
更改为self::
吗?
修改
我删除了所有static
个关键字,
class Base
{
protected $me;
protected $var_parent_1;
protected $var_parent_2;
public function __construct ($var_parent_1 = null)
{
$this->var_parent_1 = $var_parent_1;
$this->me = 'the base';
}
public function who() {
echo $this->me;
}
public function parent_1() {
echo $this->var_parent_1;
}
}
class Child extends Base
{
protected $me;
protected $var_child_1;
protected $var_child_2;
public function __construct ($var_child_1 = null)
{
parent::__construct();
$this->var_child_1 = $var_child_1;
$this->me = 'the child extends '.parent::$me;
}
// until PHP 5.3, will need to redeclare this
public function who() {
echo $this->me;
}
public function child_1() {
echo $this->var_child_1;
}
}
$objA = new Base($var_parent_1 = 'parent var 1');
//$objA->parent_1(); // "parent var 1"
//$objA->who(); // "the base"
$objB = new Child($var_child_1 = 'child var 1');
$objB->child_1(); // "child var 1"
$objB->who(); // "the child extends the base"
然后我收到此错误Fatal error: Access to undeclared static property: Base::$me in C:\wamp\www\test\2011\php\inheritence.php on line 109
,引用此行
$this->me = 'the child extends '.parent::$me;
答案 0 :(得分:1)
(简化回答,我不知道如何解释这个问题而不写20页,抱歉)。
在执行时,您的基类和子类将合并到一个对象中。在这种情况下,您的实例变量也会合并。所以,你不能调用parent :: $ avar,你只需要调用$ this-> var(因为所有vars都成为当前实例的元素)
方法的行为完全不同:因为子类应该是基类的特化,所以在基类中编写的代码不一定需要完全重写:你只需调用它并执行额外的操作操作,没有重写子类中的原始代码。
答案 1 :(得分:0)
静态属性是类的属性,而不是您使用它们创建的对象的属性。静态属性由该类的所有对象共享,并使用self ::
进行访问如果你删除静态它应该按你想要的方式工作,你会使用$ this->就像你现在一样。
答案 2 :(得分:0)
您需要阅读有关延迟静态绑定的信息
http://www.php.net/manual/en/language.oop5.late-static-bindings.php
尝试使用关键字static
但是您的课程概念有点奇怪,您还需要阅读:http://www.php.net/manual/en/language.oop5.basic.php
答案 3 :(得分:0)
请参阅此answer来解释使用self和this之间的区别。