oop - PHP empty() on __get accessor -


using php 5.3 i'm experiencing weird / non-intuitive behavior when applying empty() dynamic object properties fetched via __get() overload function. consider following code snippet:

<?php  class test {    protected $_data= array(    'id'=> 23,    'name'=> 'my string'   );    function __get($k) {     return $this->_data[$k];   }  }  $test= new test(); var_dump("accessing directly:"); var_dump($test->name); var_dump($test->id); var_dump(empty($test->name)); var_dump(empty($test->id));  var_dump("accessing after variable assignment:"); $name= $test->name; $id= $test->id; var_dump($name); var_dump($id); var_dump(empty($name)); var_dump(empty($id));  ?> 

the output of function follow. compare results of empty() checks on first , second result sets:

set #1, unexpected result:

string(19) "accessing directly:" string(9) "my string" int(23) bool(true) bool(true) 

expecting set #1 return same set #2:

string(36) "accessing after variable assignment:" string(9) "my string" int(23) bool(false) bool(false) 

this baffling , non-intuitive. object properties output non-empty strings empty() considers them empty strings. what's going on here?

based on reading of empty's manual page , comments (ctrl-f isset and/or double underscores), looks known behavior, , if want __set , __get methods , empty play nice together, there's implicit assumption implement __isset magic method well.

it little bit unintuitive , confusing, tends happen meta-programming, particularly in system php.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -