silkfire
silkfire

Reputation: 25935

How to create a dynamic property in a class?

I need to create a property called "aip-aup" in a class but I can't get it to work.

First tried to put it up with the property definitions. Unfortunately bracketed property-definitions are not allowed.

This fails (in the __construct()):

$this->${'aip-aup'} = array();

Gives error "Undefined variable 'aip-aup'".

This as well (in the __set method):

$this->${'aip-aup'}[$property] = $value;

Also tried creating a custom helper method, but does absolutely nothing:

$this->createProperty('aip-aup', array());

Any help here?

The property has to be public so should be doable?

Upvotes: 1

Views: 169

Answers (1)

Volvox
Volvox

Reputation: 1649

If you need doing something like this, then you are doing something wrong, and it would be wise to change your idea, than trying to hack PHP.

But if you have to, you can try this:

class Test {
    public $variable = array('foo'=>'bar');

public function __get($name){
    if ($name == 'aip-aup'){
        return $this->variable;
        }
    }
}   

$test = new Test();
$func = 'aip-aup';
$yourArray = $test->$func;
echo $yourArray['foo'];

Upvotes: 1

Related Questions