I had understood that the keyword "private" on a variable within a class, prevents a subclass from accessing that variable.
The code fragment below seems to show that this is not the case.
When the variables in the base class are set to private I had expected the code below to fail because the subclass wouldn't be able to access the variables in the base class.
However, I find that by using "private" the code prevents the subclass from using its own variable but allows access to the base class's variable(s).
Can anyone explain what is going on? Or am I missing something fundamental?
Thanks
MerMer
class Example //base class
{
//class-wide variables
private $var1=2;
private $var2=8;
//function to gather two numbers
function multiply_numbers()
{
$number3 = $this->var1 * $this->var2;
return($number3);
}
//function to add numbers together
function add_numbers()
{
echo $this->var1 + $this->var2;
}
}
//THIS IS THE SUBCLASS
class Example2 extends Example
{
var $var1=3;
function get()
{echo $this->var1;}
}
$example = new Example;//instatiate base class
$example2 = new Example2; //instatiate subclass
echo $example->multiply_numbers(); //returns 16
echo "<BR/>";
echo $example2->multiply_numbers(); //returns 24 s if variables in the base class are set to public but 16 if set to private!
echo "<BR/>";
echo $example->multiply_numbers(); //shows that var in main class has not been overwritten
echo "<BR/>";