In a nutshell: a class inherits a function from its parent. This function then gets called on the child, but appears to still have the scope of the parent class. Is this expected behavior?
Consider the following code example:
<?php
class OLTest {
private $var1 = 10;
public function getVar1() {
if (isset($this->var1)) {
return $this->var1;
} else {
return 'undefined';
}
}
public function getVar2() {
if (isset($this->var2)) {
return $this->var2;
} else {
return 'undefined';
}
}
}
class OLTest2 extends OLTest {
private $var1 = 11;
private $var2 = 20;
}
$oltest = new OLTest();
$oltest2 = new OLTest2();
echo "calling parent->getVar1\n";
echo $oltest->getVar1() . "\n";
echo "calling parent->getVar2\n";
echo $oltest->getVar2() . "\n";
echo "calling child->getVar1\n";
echo $oltest2->getVar1() . "\n";
echo "calling child->getVar2\n";
echo $oltest2->getVar2() . "\n";
?>
To my understanding, the output should be:
calling parent->getVar1
10
calling parent->getVar2
undefined
calling child->getVar1
11
calling child->getVar2
20
The actual output on my machine is:
calling parent->getVar1
10
calling parent->getVar2
undefined
calling child->getVar1
10
calling child->getVar2
undefined
To add to the confusion, a print_r($this) within either of the functions, will show that the scope is really set to the subclass, yet it’s impossible to access the variable.
Can someone clear this up for me?
EDIT: I am using PHP in version 5.3.3-1ubuntu9.5.
No, the output should definetly be
10, undefined, 10, undefined.The reason is that the variables that are
privateare visible only to the class defining them (not super or subclasses).So, when
childis called, its methods are defined in the parent object and when they resolvevar1orvar2they check in the scope definied forOLTest.var2is not accessible too because the declaredvar2is only visible insideOLTest2.To get your output, your should declare these variables
protectedorpublic.