PHP5.1 Reflection Reading protected Property

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jens

    PHP5.1 Reflection Reading protected Property

    Hello,

    i am just trying to get familiar with the Reflection-Api.
    I want to access a protected property of my class using the
    getValue-method of ReflectionPrope rty-Class. When i execute the code i
    get the Exception "Cannot access non-public member". Shouldnt it be
    possible to access a property from within the same class?
    Is using public getter and setter methods the only way to acces that
    property?

    Here is my code:

    thanxx

    class Test{

    /**
    * id *
    * @access protected
    * @var int
    */
    protected $id = 0;

    /**
    * Name
    *
    * @access protected
    * @var String
    */
    protected $name = null;

    protected $pkfield = null;

    /**
    * ...
    *
    *
    * @access public
    * @author
    * @return
    */
    public function __construct()
    {
    $this->pkfield="id" ;
    }

    /**
    * Die Funktion ...
    *
    *
    * @access public
    * @author
    * @return
    */
    public function check()
    {
    try{

    $rclass = new ReflectionClass (get_class());
    $prop=$rclass->getProperty($t his->pkfield);
    //Reading Value of id
    echo($this->pkfield . "=" . $prop->getValue($this ));
    }catch(Exceptio n $e1){
    echo("Error: " . $e1->getMessage() );
    }

    }
    }

  • Bart the bear

    #2
    Re: PHP5.1 Reflection Reading protected Property

    As the Good Movie says: "Blessed are the cheesemakers for they shall
    inherit
    the Earth". That, of course, applies to all producers of the dairy
    products.
    The only way you can read from a protected property is to inherit from
    the class
    (extend it). Always look on the bright side of code.

    Comment

    Working...