douxian1892 2015-03-12 13:55
浏览 110
已采纳

php oop调用私有方法

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?

  • 写回答

2条回答 默认 最新

  • drlnwji79147769 2015-03-12 13:57
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dpz1983 2015-03-12 13:57
    关注

    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();
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在工控机(Ubuntu系统)上外接USB蓝牙硬件进行蓝牙通信
  • ¥15 关于PROCEDURE和FUNCTION的问题
  • ¥100 webapi的部署(标签-服务器)
  • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)
  • ¥15 C语言除0问题的检测方法
  • ¥15 为什么四分管的内径有的是16mm有的15mm,四分不应该是12.7mm吗
  • ¥15 macos13下 ios交叉编译的问题
  • ¥15 bgz压缩文件怎么打开
  • ¥15 封装dll(引入了pcl的点云设计库)
  • ¥30 关于#开发语言#的问题:我需要在抄板的基础上再抄板抄程序,根据RDA8851CM基础上开发