How come the PHP private class var is not private?

故事扮演 提交于 2019-12-11 13:51:54

问题


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


回答1:


private keyword is about preventing the property/method from being accessed outside the class from the programming perspective. The service functions print_r and var_dump still able to see them.

So the reason is encapsulation, not literal hiding the data




回答2:


You can access anything in $GLOBALS globally, but that doesn't change the fact that the variable within the object you're getting at has its own private variables.

Simply putting an object in $GLOBALS doesn't magically make all of its member variables public. That'd be insane, and break all sorts of things. The reference to the object is what is global, nothing more.




回答3:


That's simply what GLOBALS does. It has all variables that are currently defined in the script, no matter where or how they were defined. This includes private variables.




回答4:


Built-in functions like pre(), print_r() and var_dump() are for debug purposes and therefore can show you the complete structure of any object reference it can reach. Security loophole? Maybe, simply don't let people inject code or use these commands in a production environment.



来源:https://stackoverflow.com/questions/9168159/how-come-the-php-private-class-var-is-not-private

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!