Search code examples
phpyiimagic-methods

PHP function Empty Is Not Working When Magic Method __get & __set defined in class


Currently I am working in YII framework, Where I created a class that extends CFormModel,

In that class I override the following functions:

public function __get($name)
public function __set($name, $value)

I have put the following checks in to make sure end_date and start_date aren't null

if(!empty($this->end_date) AND !empty($this->start_date))
{
      **/*Not Working*/**
      /*Some Application Logic*/
}

But it's not working properly and the condition is not getting satisfied. When I debug the code I came to know that $this->start_date and $this->end_date is not empty. Afterwards I changed the checks to the following:

if($this->end_date!='' AND $this->start_date!='')
{
      **/*Working*/**
      /*Some Application Logic*/
}

It's working as expected, but still I don't get why the empty function is not working properly. Is it because of magic method OR is there any reason for this issue?


Solution

  • You have to define a magic __isset() method for this to work.

    public function __isset($name) {
        return isset($this->data[$name]);
    }
    

    This will be triggered calls to isset() or empty() for inaccessible properties.