Search code examples
phpfieldprivate

PHP: Get list of private fields of a class (not instance!)


How can I iterate the private fields of a class without having an instance of it but just the class name? get_object_vars requires an existing instance.


Solution

  • Using: ReflectionClass

    you can simply do:

    class Foo
    {
      public    $public    = 1;
      protected $protected = 2;
      private   $private   = 3;
    }
    
    $refClass = new \ReflectionClass('Foo');
    foreach ($refClass->getProperties() as $refProperty) {
      if ($refProperty->isPrivate()) {
        echo $refProperty->getName(), "\n";
      }
    }
    

    or hide the implementation using a utility function/method:

    /**
     * @param string $class
     * @return \ReflectionProperty[]
     */
    function getPrivateProperties($class)
    {
      $result = [];
    
      $refClass = new \ReflectionClass($class);
      foreach ($refClass->getProperties() as $refProperty) {
        if ($refProperty->isPrivate()) {
          $result[] = $refProperty;
        }
      }
    
      return $result;
    }
    
    print_r(getPrivateProperties('Foo'));
    
    // Array
    // (
    //     [0] => ReflectionProperty Object
    //         (
    //             [name] => private
    //             [class] => Foo
    //         )
    // 
    // )