类无法正确获取对象的值

时间:2016-03-05 19:16:48

标签: php oop

鉴于此课程:

class Address {
  public $id;
  public $id_easypost;
  public $street1;
  public $street2;

  public function __construct($id,$id_easypost,$street1,$street2) {
      $this->$id = $id;
      $this->$id_easypost = $id_easypost;
      $this->$street1 = $street1;
      $this->$street2 = $street2;
  }
}

在创建像这样的对象时,我不明白为什么:

$ad = new Address("1", "2", "3", "4");

未正确“获取”值:

 object(Address)[15]
  public 'id' => null
  public 'id_easypost' => null
  public 'street1' => null
  public 'street2' => null
  public '1' => string '1' (length=1)
  public '2' => string '2' (length=1)
  public '3' => string '3' (length=1)
  public '4' => string '4' (length=1)

但是,这个类可以正常工作:

class Rider {
  public $id;
  public $name;
  public $activated;
  public $created_at;
  public $updated_at;

  public function __construct($id, $name, $activated, $created_at, $updated_at) {
    $this->id        = $id;
    $this->name       = $name;
    $this->activated = $activated;
    $this->created_at = $created_at;
    $this->updated_at = $updated_at;
  }
}

并正确“获取”值。

object(Rider)[16]
  public 'id' => string '1' (length=1)
  public 'name' => string '2' (length=1)
  public 'activated' => string '3' (length=1)
  public 'created_at' => string '4' (length=1)
  public 'updated_at' => string '5' (length=1)

怎么样?

1 个答案:

答案 0 :(得分:3)

您不应使用$符号来访问对象属性。这是正确的:

 $this->id = $id;