Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php classes extend

Tags:

php

class

extends

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.

like image 342
Phil Jackson Avatar asked Nov 07 '10 15:11

Phil Jackson


2 Answers

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.

like image 143
Vilx- Avatar answered Oct 02 '22 01:10

Vilx-


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;

    }

}
like image 30
Paul Dixon Avatar answered Oct 02 '22 03:10

Paul Dixon