Dave Stein
Dave Stein

Reputation: 9316

Why is getProperty returning null via PHP ReflectionClass

I am making a new ReflectionClass, then setting the protected property _products to accessible. It is always returning null Am I doing something wrong here? I am on 5.4.11

$project  = new ReflectionClass( $instance_of_object );
$property = $project->getProperty( '_products' );
$property->setAccessible( true );
$products = $property->getValue( $project );

I am trying to make sure a property is set correctly in my unit tests...

Upvotes: 4

Views: 725

Answers (1)

hek2mgl
hek2mgl

Reputation: 157947

I've prepared a working simple example. If you can execute it, there must be an error on other place in your code:

class The_Class {

    private $_products;

    public function __construct() {
        $this->_products = 'foo';
    }
}

$instance_of_class = new The_Class();
$reflClass = new ReflectionClass($instance_of_class);
$member = $reflClass->getProperty('_products');
$member->setAccessible(true);
// Here is an error in your code:
// Note that I'm using $instance_of_class, rather then
// $reflClass as argument to getValue()
var_dump($member->getValue($instance_of_class)); // string(3) "foo"

Upvotes: 2

Related Questions