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));
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.
if (empty((array)$stdClass))isEmpty()which would check properties that contain errors. Then I can just use OO approach, if I'm using objects already, and I can doif($myObject->isEmpty())or even betterif($myObject->hasErrors()). I don't see why would anyone use procedural approach at all. Avoiding setting mines removes all possibility of setting one off.emptyconstruct 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 :)