I was programming, and came across this problem:
In the code sample below, a public function sets a private varriable. Now one would expect the content of that private varriable is private, thought the $GLOBALS varriable (a superglobal) can access it, and at least read it. why? is there a way to prefent this?
<?PHP
error_reporting( E_ALL );
class test {
private $test = '';
public function test()
{
$this->test = 'Can u see me?';
}
}
$b = new test();
$b->test();
pre( $GLOBALS['b'] );
// Result:
// test Object
// (
// [test:test:private] => Can u see me?
// )
somefunc();
function somefunc()
{
pre( $GLOBALS['b'] );
// Result:
// test Object
// (
// [test:test:private] => Can u see me?
// )
}
echo $b->test;
// Result:
// Fatal error: Cannot access private property test::$test
function pre( $a ) {
echo '<pre>';
print_r( $a );
echo '</pre>';
}
?>
Thank you,
Jeffrey
privatekeyword is about preventing the property/method from being accessed outside the class from the programming perspective. The service functionsprint_randvar_dumpstill able to see them.So the reason is encapsulation, not literal hiding the data