constructor - Properties shared between child and parents class in php -


class parents{     public $a;     function __construct(){         echo $this->a;     } } class child extends parents{    function __construct(){         $this->a = 1;         parent::__construct();     } } $new = new child();//print 1 

this code above print 1,which means whenever create instance of child class,and assign value properties inherited parent,the property in parent class has been assigned.but code below shows different:

class parents{     public $a;     function test(){         $child = new child();         echo $this->a;     } }  class child extends parents{     function __construct(){         $this->a = 1;     } } $new = new parents(); $new->test();//print nothing 

where assign value child class , parent apprently didn't have value assigned child class,why?

thanks!

in top example, since construct function being called child class, treating object being used if child object using function in parent class if it's own.

in bottom example have 2 separate objects acting independently. parent object has it's $a , child, not same $a since contained in separate objects. when print $this->a in parent class, referring parent's instance of $a whereas if echo $a after setting $this->a =1 in child class display child's instance of $a.

hope cleared stuff you.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -