示例:
<?php
class Sarah {
private $Father;
private $Mother;
public function __construct() {
$this->Father = "F";
$this->Mother = "M";
}
}
class John_Connor {
private $Father;
private $Mother;
public function __construct() {
$this->Father = $this;
$this->Mother = new Sarah();
}
public function showParents() {
return get_class_vars('John_Connor');
//return get_object_vars($this);
}
}
$John = new John_Connor();
var_dump($John->showParents());
?>若使用蓝色那一行,则输出:
array(2) { ["Father"]=> object(John_Connor)#1 (2) { ["Father:private"]=> *RECURSION* ["Mother:private"]=> object(Sarah)#2 (2) { ["Father:private"]=> string(1) "F" ["Mother:private"]=> string(1) "M" } } ["Mother"]=> object(Sarah)#2 (2) { ["Father:private"]=> string(1) "F" ["Mother:private"]=> string(1) "M" } } 若使用红色那一行,则输出:
array(2) { ["Father"]=> NULL ["Mother"]=> NULL }为什么会这样,究竟get_class_vars与get_object_vars有什么区别?
<?php
class Sarah {
private $Father;
private $Mother;
public function __construct() {
$this->Father = "F";
$this->Mother = "M";
}
}
class John_Connor {
private $Father;
private $Mother;
public function __construct() {
$this->Father = $this;
$this->Mother = new Sarah();
}
public function showParents() {
return get_class_vars('John_Connor');
//return get_object_vars($this);
}
}
$John = new John_Connor();
var_dump($John->showParents());
?>若使用蓝色那一行,则输出:
array(2) { ["Father"]=> object(John_Connor)#1 (2) { ["Father:private"]=> *RECURSION* ["Mother:private"]=> object(Sarah)#2 (2) { ["Father:private"]=> string(1) "F" ["Mother:private"]=> string(1) "M" } } ["Mother"]=> object(Sarah)#2 (2) { ["Father:private"]=> string(1) "F" ["Mother:private"]=> string(1) "M" } } 若使用红色那一行,则输出:
array(2) { ["Father"]=> NULL ["Mother"]=> NULL }为什么会这样,究竟get_class_vars与get_object_vars有什么区别?
return get_object_vars($this);
array
'Father' =>
object(John_Connor)[1]
private 'Father' =>
&object(John_Connor)[1]
private 'Mother' =>
object(Sarah)[2]
private 'Father' => string 'F' (length=1)
private 'Mother' => string 'M' (length=1)
'Mother' =>
object(Sarah)[2]
private 'Father' => string 'F' (length=1)
private 'Mother' => string 'M' (length=1)return get_class_vars('John_Connor');
array
'Father' => null
'Mother' => null
这样就好理解了
get_class_vars 返回的是类定义的属性
get_object_vars 返回的是对象(实例化后的类)的属性