5

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"

2
  • 1
    How would you expect private methods to be called instead if not from public methods? Commented Aug 14, 2013 at 14:23
  • 1
    To be specific, you're NOT calling a private method, you're calling a public method that calls the private method. The public method has access to the private method, but calling $obj->echoProp(); will fail because in that case you're calling the private method. If your expectation was true, nothing would be able to call a private method. Commented Aug 15, 2013 at 2:13

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

As long as you're in the class, you can call your class' private methods on any instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.