PHP: Get list of private fields of a class (not instance!) -
how can iterate private fields of class without having instance of class name? get_object_vars
requires existing instance.
using: reflectionclass
you can do:
class foo { public $public = 1; protected $protected = 2; private $private = 3; } $refclass = new \reflectionclass('foo'); foreach ($refclass->getproperties() $refproperty) { if ($refproperty->isprivate()) { echo $refproperty->getname(), "\n"; } }
or hide implementation using utility function/method:
/** * @param string $class * @return \reflectionproperty[] */ function getprivateproperties($class) { $result = []; $refclass = new \reflectionclass($class); foreach ($refclass->getproperties() $refproperty) { if ($refproperty->isprivate()) { $result[] = $refproperty; } } return $result; } print_r(getprivateproperties('foo')); // array // ( // [0] => reflectionproperty object // ( // [name] => private // [class] => foo // ) // // )
Comments
Post a Comment