欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

用了构造函数为什么这个还是2?

程序员文章站 2022-05-06 09:44:56
...
结果为什么是2而不是5?
class a{
    public $age=2;
    public function __constrator(){
       $this->age=$age+3;
    }
    
}

$k=new a();
echo $k->age;

回复内容:

结果为什么是2而不是5?

class a{
    public $age=2;
    public function __constrator(){
       $this->age=$age+3;
    }
    
}

$k=new a();
echo $k->age;

笑死我了 __constrator 变成 __construct 以及 $this->age=$this->age+3;

class a{
    public $age=2;
    public function __constrator(){
       $this->age=$this->age+3; // 这里
    } 
    
}

$k=new a();
echo $k->age;

一下这条少了一个$this->

 $this->age=$this->age+3;
相关标签: php