Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions /

Overloading getters in DataObject not working


Reply


3 Posts   630 Views

Avatar
Urug

Community Member, 4 Posts

4 August 2013 at 2:48am

Edited: 04/08/2013 2:50am

Calling $this->Property or $this->obj('Property') in DataObject overloaded method getProperty() results in [Notice] Undefined property: DataObject::$Property.

Interesting fact: Calling $this->Nonexistent (where Nonexistent is any undefined property) doesn't result in any Notice/Error whatsoever.

Example:

class News extends DataObject {
public static $db = Array(
'Title' => 'Text',
'Content' => 'HTMLText',
);

public function getTitle() {
Debug::dump($this->Content); //works fine as we are not in getContent() method
Debug::dump($this->AnythingUndefined); //doesn't cause any trouble, returns empty string
return $this->Title; //source of the problem
}
}

using SilverStripe 3.0.5

Avatar
simon_w

Forum Moderator, 474 Posts

4 August 2013 at 8:07am

That is PHP protecting you from infinite recursion, since $this->Title would end up calling $this->getTitle(), which would access $this->Title and call $this->getTitle() and so in.

To get the actual value, use $this->getField('Title'); Likewise, in setTitle($value), you'd use $this->setField('Title', $value);

Avatar
Urug

Community Member, 4 Posts

4 August 2013 at 12:02pm

Edited: 04/08/2013 10:03pm

Thanks for the answer, it truly works, but it has a flaw. getField('Property') returns raw data, which means I can't do this for example:

public function getDate() {
return $this->getField('Date')->Day();
}


since the getField('Date') doesn't return object Date.

Nevertheless tutorial at http://doc.silverstripe.org/framework/en/topics/datamodel (section Overloading) is misleading and should be corrected imo.