Created
May 11, 2010 21:36
-
-
Save jeremeamia/397927 to your computer and use it in GitHub Desktop.
Effects of __isset() on empty()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Demonstrating how the presence of __isset() method affects accessing object members | |
class Person implements ArrayAccess { | |
protected $_data = array(); | |
public function __construct($first_name, $last_name) | |
{ | |
$this->_data['first_name'] = $first_name; | |
$this->_data['last_name'] = $last_name; | |
} | |
// Array Access Functions | |
public function offsetExists($offset) | |
{ | |
return isset($this->_data[$offset]); | |
} | |
public function offsetGet($offset) | |
{ | |
if (isset($this->_data[$offset])) | |
return $this->_data[$offset]; | |
else | |
throw new Exception; | |
} | |
public function offsetSet($offset, $value) | |
{ | |
if (isset($this->_data[$offset])) | |
$this->_data[$offset] = $value; | |
else | |
throw new Exception; | |
} | |
public function offsetUnset($offset) | |
{ | |
if (isset($this->_data[$offset])) | |
unset($this->_data[$offset]); | |
else | |
throw new Exception; | |
} | |
// Object Access Functions | |
/* I am commenting out this function to show how it affects the behavior of the empty() function. | |
* | |
* public function __isset($offset) | |
* { | |
* return isset($this->_data[$offset]); | |
* } | |
*/ | |
public function __get($offset) | |
{ | |
if (isset($this->_data[$offset])) | |
return $this->_data[$offset]; | |
else | |
throw new Exception; | |
} | |
public function __set($offset, $value) | |
{ | |
if (isset($this->_data[$offset])) | |
$this->_data[$offset] = $value; | |
else | |
throw new Exception; | |
} | |
public function __unset($offset) | |
{ | |
if (isset($this->_data[$offset])) | |
unset($this->_data[$offset]); | |
else | |
throw new Exception; | |
} | |
} | |
$Person = new Person('Jeremy', 'Lindblom'); | |
echo '<p>get_array: '; | |
var_dump($Person['first_name']); | |
echo '</p>'; | |
// This works as expected and empty() returns false. | |
echo '<p>empty_array: '; | |
var_dump(empty($Person['first_name'])); | |
echo '</p>'; | |
echo '<p>get_object: '; | |
var_dump($Person->first_name); | |
echo '</p>'; | |
// In this case empty() returns true. If we uncomment the __isset() function, it'll return false. | |
echo '<p>empty_object: '; | |
var_dump(empty($Person->first_name)); | |
echo '</p>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment