I try to access the parent's property from its extended child similar to the concept below,
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"
But I get "the child extends" instead of "the child extends the base" if I use $this->
It seems OK if I change all $this->
to self::
Why?
Is that the only proper way to access the parent's property which is to change all $this->
to self::
?
EDIT:
I removed all static
keywords,
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"
Then I get this error Fatal error: Access to undeclared static property: Base::$me in C:\wamp\www\test\2011\php\inheritence.php on line 109
which refers to this line,
$this->me = 'the child extends '.parent::$me;