We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Adding property to object during runtime

Using only PHP I'm able to do this:

class MyClass{
   public $name;
}

$foo = new MyClass();
$foo->name = 'John';
$foo->age  = 28; //A dynamic property

echo $foo->age; //Prints '28'

var_dump($foo); //obj(name, age)

However, when I try to do this using a class that extends Phalcon Model, 'age' gets set under _related as an array entry becoming accessible only via $foo->_related['age']. Is there any way to restore the default behaviour?

edited Oct '16

What ? It's impossible that it's under related. It should work as soon as age is not array or modelinterface. See this - https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model.zep#L4117

If it's indeed array or modelinterface you can either use writeAttribute method or extend __set method

Hmm, interesting. I was using an array in my source code... Going to check writeAttribute and get back to you.

What ? It's impossible that it's under related. It should work as soon as age is not array or modelinterface. See this - https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model.zep#L4117

If it's indeed array or modelinterface you can either use writeAttribute method or extend __set method

edited Oct '16

I just tried

$vq = new VideoQuestion();
$vq->writeAttribute('foo',[]);
var_dump($vq->foo);
die;

and the result is

Notice: Access to undefined property VideoQuestion::foo in

I also tried

$vq = new VideoQuestion();
$vq->foo = []; //NEW LINE HERE
$vq->writeAttribute('foo',[]);
var_dump($vq->foo);
die;

and got the same result. However, when I tried

$vq = new VideoQuestion();
$vq->foo = '';
$vq->writeAttribute('foo',[]);
var_dump($vq->foo);
die;

The output was array (size=0) empty as expected...

What ? It's impossible that it's under related. It should work as soon as age is not array or modelinterface. See this - https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model.zep#L4117

If it's indeed array or modelinterface you can either use writeAttribute method or extend __set method

Why you just can't add proper property ? Adding dynamic properties is heavy in php. If this doesn't work then override __set