note 129001 added to function.property-exists

From: Date: Sun, 05 Nov 2023 17:05:03 +0000
Subject: note 129001 added to function.property-exists
Groups: php.notes 
Request: Send a blank email to php-notes+get-220957@lists.php.net to get a copy of this message
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 // returns true if property is safely accessible publicly by using $obj->$prop // Tested with PHP 5.1 - 8.2, see https://3v4l.org/QBTd1 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(); } //// Test/demo 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"; } /* $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. */ ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.157.134 (proxied: 94.21.230.235) ---- Manual Page -- https://php.net/manual/en/function.property-exists.php Edit -- https://main.php.net/note/edit/129001 Del: integrated -- https://main.php.net/note/delete/129001/integrated Del: useless -- https://main.php.net/note/delete/129001/useless Del: bad code -- https://main.php.net/note/delete/129001/bad+code Del: spam -- https://main.php.net/note/delete/129001/spam Del: non-english -- https://main.php.net/note/delete/129001/non-english Del: in docs -- https://main.php.net/note/delete/129001/in+docs Del: other reasons-- https://main.php.net/note/delete/129001 Reject -- https://main.php.net/note/reject/129001 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#220957) next »