There is a class:

class VideoModel extends BaseModel { ... protected $youtubeId; protected function setYouTubeId($value) { if (!empty($value)) { $this->setUploadedAt(date('Ymd H:i:s')); $this->youtubeId = $value; return true; } return false; } } class BaseModel { ... public function __get($field) { // check if getter exists $getterName = 'get'.ucfirst($field); if (method_exists($this, $getterName)) { return $this->$getterName(); } if (isset($this->$field)) { return $this->$field; } return null; } } 

This code does not work as expected:

 >> var_dump($webinar->youtubeId); string 'rzCGzjbyQjc' (length=11) >> var_dump(empty($webinar->youtubeId)); boolean true 
  • (isset($this->$field)) in the code I see isset and where do you check empty why? - Naumov
  • @Naumov the second part of the code is used in the controller to determine which view to use (the real code looks like this: if (!empty($webinar->youtubeId)) { include '_webinarPlayer.php'; } else { include '_waitForRecord.php'; } ). - Makarenko_I_V
  • var_dump right before if what does it say? not in console xdebug - Naumov

1 answer 1

For empty, this is a completely explainable behavior. When using it, the __get magic method is not called, and since the protected property is not available for the empty function, we get true.

You need to define the __isset magic method in the class, which will check the property when the isset or empty constructs are called to it.

http://php.net/__isset

Although, on reflection, I doubted that __isset would help you. It only determines the existence of the property. Perhaps more correctly, in your case, it will save the property value to a variable and work with it already:

 $youtubeId = $webinar->youtubeId; var_dump($youtubeId); var_dump(empty($youtubeId)); 
  • one
    Checked, really __get is not called for empty. I corrected your answer, in fact, the field exists but is closed by the scope from accessing it from outside. - Makarenko_I_V
  • Thank you, valuable editing. I did not pay attention to it. - Ivan Pshenitsyn
  • 2
    empty first calls __isset, if __isset says true, then it calls __get. Both methods must be implemented. - Small
  • @ Minor checked, you are absolutely right. - Makarenko_I_V