简体   繁体   中英

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).

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
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM