3v4l.org

run code in 300+ PHP versions simultaneously
<?php // returns true if property is safely accessible publicly by using $obj->$prop: function public_property_exists( $obj, $prop ){ // allow magic $obj->__isset( $prop ) to execute if exists if( isset( $obj->$prop )) return true; // no public/protected/private property exists with this name if( ! property_exists( $obj, $prop )) return false; // the property exists, but is it public? $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"; }
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
$o->public is a public property, its value is: 'I’m public!' $o->protected is not a public property. $o->private is not a public property. $o->magic is a public property, its value is: 'I’m magic!' $o->magic_isset_but_null is a public property, its value is: NULL $o->missing is not a public property.

preferences:
88.11 ms | 406 KiB | 90 Q