Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 754
sarvesh Avatar asked Dec 16 '12 13:12

sarvesh


People also ask

What is __ method __ in PHP?

__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that. __FUNCTION__ returns only the name of the function. while as __METHOD__ returns the name of the class alongwith the name of the function.

What is __ get in PHP?

From the PHP manual: __set() is run when writing data to inaccessible properties. __get() is utilized for reading data from inaccessible properties.

How do you empty a function in PHP?

PHP empty() FunctionThe empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.

What are PHP magic methods functions?

Magic methods are special methods which override PHP's default's action when certain actions are performed on an object. Caution. All methods names starting with __ are reserved by PHP. Therefore, it is not recommended to use such method names unless overriding PHP's behavior.


1 Answers

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.

like image 93
Sherif Avatar answered Sep 22 '22 23:09

Sherif