class pig{
//猪的属性
public $name;
public $weight;
public $color;
public $age;
//成员方法
public function addweight($a){
    $this->weight=$weight+$a;
}
}
$pig1=new pig();
$pig1->weight=100;
 $pig1->addweight(5);
 echo $pig1->weight;
这样的结果是Notice: Undefined variable: weight in D:\WWW\lianxi.php on line 10
5然后我把  $this->weight=$weight+$a;换成$this->weight+=$a;结果就是正确的105,我想问的是为什么$this->weight=$weight+$a这样是不可以的,求解答,谢谢

解决方案 »

  1.   

    $this->weight=$this->weight+$a
    这样才是正确的
      

  2.   

    在类方法中访问类的属性要用 $this ,如 $this->weight
      

  3.   

    class pig{
    //猪的属性
    public $name;
    public $weight;
    public $color;
    public $age;
    //成员方法
    public function addweight($a){
        $this->weight=$weight+$a;        不能这么写
    }
    }
    $pig1=new pig();
    $pig1->weight=100;
     $pig1->addweight(5);
     echo $pig1->weight;