简体   繁体   中英

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?

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.

Private can only be used in the class itself.

Protected can only be used in the class itself and child classes.

Public can be used anywhere.

class a {

    private $one;

    public function abc() { //notice the public

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM