1

I'm facing this dilemma, basically I want to create an error object if a certain task isn't met. Now to understand what I've got to send back to the user, I need to check to see if that error object is either empty or has data. The issue is this:

$obj = new stdClass();
var_dump(empty($obj)); // returns false

As you can see in this example, it's returning false instead of true as it's empty.

$o = new stdClass();
$a = array();

var_dump(empty($o));
var_dump(empty($a));

Example

This works perfectly fine for an array, but does anyone know why this is happening for objects?


I've read answers like this which state to cast it as an array, but my question is this:

Why does it return false when it's empty? What is the logic behind it? If I wanted an array, I would've started with that.

9
  • 5
    RTM Also see: php.net/manual/en/types.comparisons.php Commented May 20, 2015 at 10:37
  • 1
    If you really need to check if an object is empty, just cast it to an array: if (empty((array)$stdClass)) Commented May 20, 2015 at 10:41
  • 2
    If I were you and if I coded what you did, I'd have my object implement method isEmpty() which would check properties that contain errors. Then I can just use OO approach, if I'm using objects already, and I can do if($myObject->isEmpty()) or even better if($myObject->hasErrors()). I don't see why would anyone use procedural approach at all. Avoiding setting mines removes all possibility of setting one off. Commented May 20, 2015 at 10:46
  • 1
    @Darren - we often miss the forest because of the damn trees, but coffee should help with that. Anyway, glad I could help a bit :> Commented May 20, 2015 at 10:51
  • 1
    It's all good, the question was about empty construct and objects so the provided answer is answering that, for any future googlers that stumble upon here so it's all good if you ask me. I'm ok with helping you, no need for any imaginary points :) Commented May 20, 2015 at 10:53

1 Answer 1

2

From php.net:

The following things are considered to be empty:

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

Every object you create won't be "empty".

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

Comments

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.