对私有方法的php oop调用
我有一节课是这样的对私有方法的php oop调用,php,oop,Php,Oop,我有一节课是这样的 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()时发现了一个致命错误。它说从上下文调用私有方法xxx 我对oop的了解是非常新的
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()时发现了一个致命错误。它说从上下文调用私有方法xxx
我对oop的了解是非常新的,私有方法/属性只能在同一个类中使用。但是,我不能调用abc(),即使它在同一个类中
为什么会这样?因为您没有在类内调用方法,您在类代码之外这样做
$call = new a;
$call->abc()->other_function();
这在类的上下文之外,这就是为什么会出现致命错误。
Private
只能在类本身中使用
Protected
只能在类本身和子类中使用
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();
您可以在类内调用它。不在它之外。要在课堂外称呼它,它必须是公开的。谢谢你的洞察力。不知道为什么我会因为有点无知而得到-1…我试图寻找答案,但找不到明确的答案@安德烈。如果我要返回多个属性,我将如何执行此操作?谢谢:)将要返回的属性封装到
数组中,然后返回该数组,但这已经是另一个问题了。