我需要一种方法来判断在类外部访问属性是否会发生错误/警告,考虑到类可能使用 __isset/__get 魔术方法来模拟不存在的属性。
<?php
function public_property_exists( $obj, $prop ){
if( isset( $obj->$prop )) return true;
if( ! property_exists( $obj, $prop )) return false;
$rp = new ReflectionProperty( $obj, $prop );
return $rp->isPublic();
}
class C {
public $public = "I’m public!";
protected $protected = "I’m public!";
private $private = "I’m public!";
function __isset( $k ){
return substr( $k, 0, 5 ) === 'magic';
}
function __get( $k ){
if( $k === 'magic_isset_but_null') return null;
return "I’m {$k}!";
}
}
$o = new C();
foreach( array(
'public', 'protected', 'private',
'magic', 'magic_isset_but_null',
'missing'
) as $prop ){
if( public_property_exists( $o, $prop ))
echo "\$o->{$prop} is a public property, its value is: ",
var_export( $o->$prop, true ), "\n";
else echo "\$o->{$prop} is not a public property.\n";
}