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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Overloading getters in DataObject not working


Go to End


4 Posts   3990 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
(deleted)

Community Member, 473 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.

Avatar
Fuzz10

Community Member, 791 Posts

3 December 2015 at 4:14am

Just bumping this. It seems this is still the case in 3.2