我嘗試從它類似於下面的概念擴展孩子訪問父母的財產訪問父母的財產,OOP:問題從擴展子
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->
如果我改變似乎OK所有$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;
您確定要將這些設置爲「靜態」嗎? – jtbandes
不確定...我實際上覆制並修改了這個http://stackoverflow.com/questions/831555/php-child-class-accessing-parent-variable-problem – laukok