I needed a method for finding out if accessing a property outside a class is possible without errors/warnings, considering that the class might use the magic methods __isset/__get to simulate nonexistent properties.
<?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";
}