It's working exactly the way it should be. Setting a property to private will does not stop it from being inherited.The only difference between private and protected is whether or not a child class has
direct access to it's value.
That's what I was trying to confirm. It made sense to me from the onset, but it also seemed 'wasteful' as inaccessible properties still get stored in child classes ( if that's makes sense)
I do have ONE QUESTION remaining, and that is inherited method seem to act as if they were in the parent class ( and as such they have access to properties or property values set at the parent scope
Perhaps this is not what inheritance was meant for and am wrong for thinking this way.. which was that an inherited method had teh current scope, not the scope of the parent. The reason I find it cumbersome otherwise is because( as you essentially utilized this in your example) the magic variable $this->... will always point to the class from which the method was inherited and NOT the current class... unless the method is copied in the new class ( which really doesnt do much for cutting down code or redundancy.
This is what I mean:
PHP Code:
class Test1 {
private $name;
private $value= 10;
public function output()
{
echo $this->value . '<br />'; //
}
}
class Test2 extends Test1 {
private $value=5; // for the sake of example, lets say $value must be '5' anytime an intance of Test2 is dealt with.
}
$test = new Test2();
$test->output(); // will display the 'value' property of the class ; one would expect '10' if Test1, '5' if Test2.
This works, however if we rewrite the function again in the child class ( of course doing so defeats any attempt at code frugality and makes the code redundant)
PHP Code:
class Test1 {
private $name;
private $value= 10;
public function output()
{
echo $this->value . '<br />'; //
}
}
class Test2 extends Test1 {
private $value=5;
public function output()
{
echo $this->value . '<br />'; //
}
}
$test = new Test2();
$test->output(); // will display the 'value' property of the class ; one would expect '10' if Test1, '5' if Test2.
It seems a simple enough fix to just make $value protected , instead of public, but what if $value is not supposed to be present at all in TEST 2?
PHP Code:
class Test1 {
private $name;
private $value= 10;
public function output()
{
echo $this->value . '<br />'; //
}
}
class Test2 extends Test1 {}
$test = new Test2();
$test->output();
I still outputs 1) and unsetting $value in Test2 wouldn't help, as the function is actually running in Test1 and acting on the properties of Test1, even tho its an instance of Test2. I hope my question makes sense...
Bookmarks