是否可以轻松快速地“将一个对象的属性分配给另一个对象”
class a {
public $number_one;
public $number_two;
public $number_three;
function __contruct() {
//do stuff
}
}
class b {
public $my_var;
function __contruct() {
$instanc_a = new a();
extract( $instance ); // but make these extracted object properties of class b????
// how? :-(
echo $this->number_one;
}
}
答案 0 :(得分:2)
您可以使用get_object_vars
将class a
的公共(仅限)属性复制到当前对象:
class b {
public $my_var;
function __construct() {
$instanc_a = new a();
$vars = get_object_vars($instanc_a);
foreach($vars as $name => $value) {
$this->$name = $value;
}
echo $this->number_one;
}
}
<强> See it in action 强>
注意:您的代码中有一个拼写错误(两个“contruct”而不是“construct”),这会阻止事情按预期工作。
答案 1 :(得分:0)
听起来您实际上希望class b
扩展class a
class b extends a {
public $my_var;
function __construct () {
parent::__construct();
// Now $this refers to anything in class b, or if it doesn't exist here, looks to class a for it
echo $this->number_one;
}
}