Dec
3 d.
2007

Private PHP class variables exposed

Rimvydas Paškevičius reported a way to access private and protected vars from outside of class scope. Do you think it’s a PHP bug? It works for me on PHP 5.2.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class aaa {
 
    protected $_parent = null;
    private $_value = 5;
 
    function setParent( $oParent ) {
        $this->_parent = $oParent;
    }
 
    function getParent() {
        return $this->_parent;
    }
 
    function showParentValue() {
        echo "parent value: ", $this->_parent->_value;
    }
}
 
$aa = new aaa;
$bb = new aaa;
 
$bb->setParent($aa);
$bb->showParentValue();

Responses

  1. Dominykas says:

    I am almost sure this works the same way in Java. If you think about it - this is not outside of the class scope - it’s outside of object scope.

  2. Tomas says:

    Domai, yes you are right. Indeed it is outside object scope, but is called from within the same class and that’s a language feature. This has been discussed in PHP internals. Thanks Marco Kaiser for posting and making it clear.

Leave a Reply