brazorf
brazorf

Reputation: 1951

PHP empty($string) return true but string is not empty

<?php
$m->type = 'EVENT';
if (empty($m->type)) {
  var_dump($m->type);
}
?>

This piece of code prints

string(5) "EVENT"

How is this possible?

edit

The $m object is a plain one, with magic __set and __get that store values into a protected array.

<?php
$m->type = 'EVENT';
if ($m->type == NULL) {
  var_dump($m->type);
}
?>

The above mentioned code works as expected (it skips the if body).

Upvotes: 1

Views: 2222

Answers (1)

usoban
usoban

Reputation: 5478

If you're using magic getter within your class, the docs page documents a rather tricky behaviour:

<?php
class Registry
{
    protected $_items = array();
    public function __set($key, $value)
    {
        $this->_items[$key] = $value;
    }
    public function __get($key)
    {
        if (isset($this->_items[$key])) {
            return $this->_items[$key];
        } else {
            return null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // true, .. say what?
$tmp = $registry->notEmpty;
var_dump(empty($tmp)); // false as expected
?>

Upvotes: 11

Related Questions