今天查看yii源碼,發現yiiaseModel中的attribute()方法是通過反射獲取對象的public non-static屬性。記得以前看到的代碼都是用get_object_vars()這個函數獲取的,昨天查看php文檔,發現還可以用foreach遍歷對象屬性。於是寫個例子練習下。
class TestClass {
private $a;
protected $b;
public $c;
public $d;
public static $e;
private function funcA() {
}
protected function funcB() {
}
public function funcC() {
}
public function getPropertyMethodOne() {
echo "[get_object_vars]", PHP_EOL;
$vars = get_object_vars($this);
foreach ($vars as $k => $v) {
echo $k, ' => ', $v, PHP_EOL;
}
}
public function getPropertyMethodTwo() {
echo "[foreach object]", PHP_EOL;
foreach ($this as $k => $v) {
echo $k, ' => ', $v, PHP_EOL;
}
}
public function getPropertyMethodThree() {
echo "[reflection]", PHP_EOL;
$class = new ReflectionClass($this);
foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
if (!$property->isStatic()) {
echo $property->getName(), ' => ', $property->getValue($this), PHP_EOL;
}
}
}
}
$obj = new TestClass();
echo "[get_object_vars]", PHP_EOL;
$vars = get_object_vars($obj);
foreach ($vars as $k => $v) {
echo $k, ' => ', $v, PHP_EOL;
}
echo "[foreach object]", PHP_EOL;
foreach ($obj as $k => $v) {
echo $k, ' => ', $v, PHP_EOL;
}
echo "[reflection]", PHP_EOL;
$class = new ReflectionClass($obj);
foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
if (!$property->isStatic()) {
echo $property->getName(), ' => ', $property->getValue($obj), PHP_EOL;
}
}
輸出:
[get_object_vars]
c =>
d =>
[foreach object]
c =>
d =>
[reflection]
c =>
d =>
可見,當著三種方法用在類的外部時,結果是一樣的。get_object_vars()和foreach是獲取到的是對象的public non-static屬性,而通過反射的話則需要手動篩選出public non-static屬性。
$obj = new TestClass();
$obj->getPropertyMethodOne();
$obj->getPropertyMethodTwo();
$obj->getPropertyMethodThree();
輸出
[get_object_vars]
a =>
b =>
c =>
d =>
[foreach object]
a =>
b =>
c =>
d =>
[reflection]
c =>
d =>
可見,get_object_vars()和foreach用在類內部時,private、protected、public的實例屬性都能獲取到。反射就不用說了,通過手動篩選,各種類型的屬性都能獲取到。