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

5
  • Doesn't do that for me, I'm afraid (PHP 5.3.24) Commented Jun 4, 2013 at 13:21
  • Have you tried storing that string into a variable and then testing it? Like this: $string = $m->type; if(empty($string)){ //code here } Commented Jun 4, 2013 at 13:21
  • 1
    Try $someVar=$m->type; if (empty($someVar)) { var_dump($m->type); } and tell us, what you get Commented Jun 4, 2013 at 13:22
  • 3
    What is $m? (ie: what class?) This doesn't happen with a stdClass, so the type of $m is probably a pretty big factor. Commented Jun 4, 2013 at 13:22
  • Is this the only piece of the code or have you just posted a subset? If there is more, a larger context may help Commented Jun 4, 2013 at 13:22

1 Answer 1

11

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
?>
Sign up to request clarification or add additional context in comments.

3 Comments

I think this may be what's affecting my code. I'll check it out.
so use empty($m = $m->type) instead of empty($m->type), and it will work correctly
@Roman please don't, inline assignments are classical code smell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.