Php 类不';无法正确获取对象';s值
鉴于这一类别:Php 类不';无法正确获取对象';s值,php,oop,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; $thi
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(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)
这是怎么回事?您不应该使用
$
符号访问对象属性。这是正确的:
$this->id = $id;
谢谢。那简直是个打字错误!额外问题:object(Address)[15]或object(Rider)[16]中的数字是什么意思?