In the example below I receive an error stating the value of $foo->_test is not accessible since it is private. What am I doing wrong?
<?php
$foo = new Bar;
$foo->test();
print_r( $foo->_test );
class Foo
{
private $_test = array();
}
class Bar extends Foo
{
public function test()
{
$this->_test = 'opa';
}
}
?>
Any help is appreciated.
Private variables are only visible to the direct class in which they are declared. What you’re looking for is
protectedWithout this you are effectively creating two different member variables in your object.[edit]
You’re also attempting to access a private (soon to be protected) member variable outside the class completely. This will always be disallowed. Except in this case, you’re creating a second,
publicmember variable which is why there is no error displayed. You didn’t mention that you expected to see an error, so I’m assuming this is a question you had.[edit]
here is the var dump:
[edit]
One thing I’ve done in a framework I wrote is to create a base class that I extend almost everywhere. One thing this class does is use the
__getand__setmethods to enforce declaring class member variables – it helps narrow down code problems such as the one you had.