Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top