0

I am within a class. I try to set an object member:

$this->list = "hello";
print $this->list;

It returns "hello";

However, empty($this->list)) always return true.

But for non object member $tmp = "hello", empty($tmp) return false.

Why empty() cannot be used on object member?

Update: empty() is influenced by the the my code framework. That is why it does not work properly.

3
  • 1
    You need to provide some code, are you actually within a class or trying to create an object just through $this->list = 'hello'? Are you getting any error messages? Commented Jul 5, 2011 at 14:29
  • Cannot reproduce: $s = new stdClass; $s->list = 'Hello'; var_dump($s); /* object(stdClass)#1 (1) { ["list"]=> string(5) "Hello" } */ var_dump(empty($s->list)); /* bool(false) */ Commented Jul 5, 2011 at 14:33
  • I used var_dump($this->list). It returns "string(5) hello". But empty($this->list) still return true Commented Jul 5, 2011 at 14:36

1 Answer 1

2
<?php

  class Foo
  {
    var $bar;

    function Bar()
    {
      $this->bar = 'hello';
      echo "In class: " . (empty($this->bar) ? 'empty' : 'populated') . "\r\n";
    }
  }

  $foo = new Foo();
  $foo->Bar();

  echo "Out of class: " . (empty($foo->bar) ? 'empty' : 'populated');

Output:

In class: populated
Out of class: populated

Not sure what you mean. Maybe provide more code? Also, per the empty() manual, the following values are to be considered empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float) 9 "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

Also, try using var_dump on the object to confirm it's what you're expecting.

Sign up to request clarification or add additional context in comments.

3 Comments

I used var_dump($this->list); empty($this->list); It returns string(5) hello true.
@chnet: That's interesting, it's got to have somethign else interfering. Just through a basic test (above) there is no issue with testing against object members.
@chnet: you ever discover the issue?

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.