phpoopmethod-chaining

php oop Call to private method


I have a class that look like this

class a {

    private $one;

    private function abc() {

    $this->one = "I am a string";
    return $this;
}

$call = new a;
$call->abc()->other_function();

As I was doing matutor method, php has caught a fatal error on calling function abc(). It said Call to private method xxx from context.

What I know of oop is very new, that private method/property can only be used within the same class.However, I cannot call the abc() even it is within the same class.

How come?


Solution

  • Because you are not calling the method inside the class you are doing so outside the class code.

    $call = new a;
    $call->abc()->other_function();
    

    this is outside the context of the class, and this is why you get a Fatal Error.