Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP class private property and method

Noticed something about PHP's classes and I don't know if it's a bug or why it works, this is the code:

<?php
class A {
    private $prop = 'value';

    public function fun()
    {
        $obj = new A;
        $obj->echoProp();
    }

    private function echoProp()
    {
        echo 'Prop has value: '.$this->prop;
    }
}

$obj = new A;
$obj->fun();

And the result isn't an error as I was expecting since I'm calling a private method (tested on PHP 5.3.10-1ubuntu3.7 with Suhosin-Patch). The result is "Prop has value: value"

like image 307
Emi Avatar asked Oct 03 '22 06:10

Emi


1 Answers

At the php documentation http://www.php.net/manual/en/language.oop5.visibility.php#language.oop5.visibility-other-objects it says:

Visibility from other objects

Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.

So this isn't a bug but a wanted feature of php.

like image 79
benestar Avatar answered Oct 05 '22 19:10

benestar