i have two classes one parent and the other extends , I need to use main vars in extended class. for example
class parentClass
{
$this->value = null
function __construct()
{
echo "im parent" ;
}
}
class childClass extends parentClass
{
function sayIt()
{
var_dump($this->value);
}
}
$p = new parentClass ;
$p->value = 500 ;
$c = new childClass ;
$c->sayIt(); // this output null ! i want it to output 500 , how i can do that
thanks
that's not the way inheritance works. The
childClass
is not automatically connected to the parent class, it just inherits from theparentClass
it just inherits all public and protected variables/methods from teh parent. It is not connected to the parent's instances.if you wnat it to output 500 you have to assign it to the child class instance somehow:
If you need a variable shared between all classes and instances you can use a
static
variable.you are confusing with class constructs and references.
$p
is an instance of the parentclass.$c
is an instance of the childclass.they don't share their data.
Bad Bad Bad The code is strictly for educational purpose i would advice you to get a book on basic Principles of Object Oriented programming
Making your variable static would make it accessible via the child class