Hi I have a question regarding $this.
class foo {
function __construct(){
$this->foo = 'bar';
}
}
class bar extends foo {
function __construct() {
$this->bar = $this->foo;
}
}
would
$ob = new foo();
$ob = new bar();
echo $ob->bar;
result in bar
??
I only ask due to I thought it would but apart of my script does not seem to result in what i thought.
To quote the PHP manual:
Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
This means that in your example when the constructor of bar
runs, it doesn't run the constructor of foo
, so $this->foo
is still undefined.
PHP is a little odd in that a parent constructor is not automatically called if you define a child constructor - you must call it yourself. Thus, to get the behaviour you intend, do this
class bar extends foo {
function __construct() {
parent::__construct();
$this->bar = $this->foo;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With