php oop 调用私有方法

php oop Call to private method

我有一个 class 看起来像这样

class a {

    private $one;

    private function abc() {

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

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

当我在执行 matutor 方法时,php 在调用函数 abc() 时发现了一个致命错误。它说 Call to private method xxx from context.

我对 oop 的了解非常新,private method/property 只能在同一个 class.However 中使用,即使在同一个 [=23] 中我也不能调用 abc() =].

怎么会?

因为您没有在 class 的 内部调用方法 class,所以您在 class 代码之外这样做。

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

这超出了 class 的上下文,这就是您收到致命错误的原因。

Private 只能用在 class 本身。

Protected 只能用于 class 本身和子 classes.

Public可以在任何地方使用。

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();