Skip to content
Advertisement

Instantiate object from an accessor

I have a strange issue with php and instantiating objects:

Background

There’s a class structure I’ve created (some interfaces, some traits etc) where I automatically extend a class with a whole load of functions etc. These are working as expected in almost all scenarios.

I’ve attempted to close things down to “idiot/public” proof this repo, so I have made sensitive properties/methods private/protected.

This set of functions include object generation and it is done something like as follows:

$object_name = 'SomeClass';

$new_object = new $this->object_name;

// $new_object is successfully instantiated

(obviously this is done over a few files, so I’m simplifying as it completely illustrates the issue)

So, in their various classes and for various inheritance/anti-pebkac reasons I want to do the following:

// define accessors
// ...

$this->setObjectName('SomeClass');


$new_object_direct = new $this->object_name;
$new_object_accessor = new $this->getObjectName();

// $new_object_direct is successfully instantiated
// $new_object_accessor errors!

This last line generates an error:

ErrorException: Undefined property: (...)SomeController::$getObjectName

If you do the following:


$this->setObjectName('SomeClass');

var_dump($this->object_name, $this->getObjectName())


.. it outputs:

... : string 'SomeClass'
... : string 'SomeClass'

Both are exactly the same.

Question

How do you instantiate an object from a string accessor?

Advertisement

Answer

After some messing around, I discovered that this needs to be done on separate lines:

// define accessors
// ...

$this->setObjectName('SomeClass');


$new_object_direct = new $this->object_name;

$name = $this->getObjectName();
$new_object_accessor = new $name;

// $new_object_direct is successfully instantiated
// $new_object_accessor is successfully instantiated

I will raise this as a bug in php.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement