Reputation: 21
I currently have two classes, one called Dog, one called Poodle. Now how can I use a variable defined in Dog from the Poodle class. My code is as follows:
class dog {
protected static $name = '';
function __construct($name) {
$this->name = $name
}
}
class Poodle extends dog {
function __construct($name) {
parent::__construct($name)
}
function getName(){
return parent::$name;
}
}
$poodle = new Poodle("Benjy");
print $poodle->getName();
I get this error
Notice: Undefined variable: name
Upvotes: 0
Views: 3539
Reputation: 53940
i guess 'name' is an attribute of the concrete Dog, so it shouldn't be static in the first place. To access non-static parent class attributes from within an inherited class, just use "$this".
class dog {
protected $name = '';
function __construct($name) {
$this->name = $name;
}
}
class Poodle extends dog {
function getName(){
return $this->name;
}
}
Upvotes: 5
Reputation: 18523
In your dog class you have declared the variable $name as static, you have to declare the variable without the static word
class dog {
protected $name = '';
function __construct($name) {
$this->name = $name
}
}
class Poodle extends dog {
function __construct($name) {
parent::__construct($name)
}
function getName(){
return $this->name;
}
}
$poodle = new Poodle("Benjy");
print $poodle->getName();
Upvotes: 0
Reputation: 37803
The problem is in your Dog
constructor. You wrote:
$this->name = $name;
But using $this
implies that name
is an instance variable, when in fact it's a static variable. Change it to this:
self::$name = $name;
That should work fine.
Upvotes: 2