Memory App
Programming
 




Get private property


<?php
    class Foo {
        public    $foo  = 1;
        protected $bar  = 2;
        private   $baz  = 3;
    }

    $foo = new Foo();
    
    // echo $foo->baz;
    // Fatal error: Cannot access private property

    $reflector = new ReflectionObject($foo);

    $property = $reflector->getProperty('baz');
    $property->setAccessible(true);

    echo $property->getValue($foo);
        // display 3
(1/3)

Get private properties


<?php
    class Foo {
        public    $foo  = 1;
        protected $bar  = 2;
        private   $baz  = 3;
    }

    $foo = new Foo();

    $reflector = new ReflectionObject($foo);
    $properties = $reflector->getProperties(ReflectionProperty::IS_PRIVATE | 
                       ReflectionProperty::IS_PROTECTED);
    array_map(function(&$x) { $x->setAccessible(true); }, $properties);
    var_dump($properties);
    /*
        array (size=2)
          0 => 
            object(ReflectionProperty)[3]
              public 'name' => string 'bar' (length=3)
              public 'class' => string 'Foo' (length=3)
          1 => 
            object(ReflectionProperty)[4]
              public 'name' => string 'baz' (length=3)
              public 'class' => string 'Foo' (length=3)
    */
(2/3)

Get parent properties


<?php
    class Ford { 
      private $model;
      protected $foo;
      public $bar;
    }

    class Car extends Ford {
      private $year;
    }

    $class = new ReflectionClass('Car');
    var_dump($class->getProperties()); // First chunk of output
    var_dump($class->getParentClass()->getProperties()); // Second chunk
http://php.net/manual/ro/reflectionclass.getproperties.php http://stackoverflow.com/questions/9913680/does-reflectionclassgetproperties-also-get-properties-of-the-parent

Questions



Top Reference > Programming
0/0 (80)  
Not Logged