Reputation: 2071
I have this abstract class
abstract class Guitar {
protected $strings;
public function __construct($no_of_strings) {
$this->strings = $no_of_strings;
echo 'Guitar class constructor is called <br/>';
}
abstract function play();
}
And child class,
class Box_Guitar extends Guitar {
public function __construct($no_of_strings) {
echo 'Box Guitar constructor is called <br/>';
$this->strings = $strings + 100;
}
public function play() {
echo 'strumming ' . $this->strings;
}
}
Then I initiated the class with,
$box_guitar = new Box_Guitar(6);
And my out put was
Box Guitar constructor is called
Guitar class constructor is called
strumming 106
So my question is why parent constructor is called? I didn't use Parent::__construct().
Upvotes: 0
Views: 105
Reputation: 2071
Thanks @jcsanyi. There was my fault. I have another class called,
class Electric_Guitar extends Guitar {
public function play() {
return 'Plug to current : '. $this->strings;
}
}
This has not any constructor. When I invoking objects, I used both of them.
$box_guitar = new Box_Guitar(6);
$elec_guitar = new Electric_Guitar(5);
So the abstrct constructor was called by elec_guitar object.
Upvotes: 0
Reputation: 8174
It's not.
When I run the code you gave above, I get this output:
Box Guitar constructor is called
Notice: Undefined variable: strings in /test/test.php on line 19
Double-check that you're not running an old version of the files or something. Did you forget to save or upload some changes?
For the record, once you figure out why you're getting the unexpected behaviour, the right way to write the Box_Guitar
constructor will probably look something like this:
public function __construct($no_of_strings) {
echo 'Box Guitar constructor is called <br/>';
parent::__construct($no_of_strings + 100);
}
Upvotes: 1