PHP獲取物件屬性的三種方法,具體如下:
今天檢視yii原始碼,發現yii\base\Model中的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的例項屬性都能獲取到。反射就不用說了,透過手動篩選,各種型別的屬性都能獲取到。