Why can't I call property_exists on stdClass?
Asked Answered
E

3

7

Here is my code:

<?php

$madeUpObject = new \stdClass();
$madeUpObject->madeUpProperty = "abc";

echo $madeUpObject->madeUpProperty;
echo "<br />";

if (property_exists('stdClass', 'madeUpProperty')) {
    echo "exists";
} else {
    echo "does not exist";
}
?>

And the output is:

abc does not exist

So why does this not work?

Expiratory answered 1/2, 2013 at 21:6 Comment(5)
Because the made up property isn't defined in stdClass, but $madeUpObject?Bully
@Pekka웃 Isn't $madeUpObject an instance of stdClass?Expiratory
Sure, but setting a property on an instance is not going to change the class definition, is it?Bully
@Pekka웃 When you do not have a property in a class but access $instanceOfThatClass->nonExistingProperty, a public field is generated by php.Expiratory
Yes but not in the class definition of stdClassBully
M
14

Try:

if( property_exists($madeUpObject, 'madeUpProperty')) {

Specifying the class name (instead of the object like I have done) means in the stdClass definition, you'd need the property to be defined.

You can see from this demo that it prints:

abc
exists 
Mawson answered 1/2, 2013 at 21:9 Comment(4)
So $madeUpObject is an instance of class madeUpObject ?Expiratory
No, it's an instance of stdClass. You're setting a property dynamically (which isn't specified in the class defintion of stdClass). That's why you can't specify the class name as a string to property_exists(). You need to give it the newly created object, since that object is the only thing that has the newly created property.Mawson
Interesting. So the class does not have the field, but the object does.. Thanks.Expiratory
I came to this article just to realize that I have been using the call arguments in the wrong order!Pastorate
G
5

Because stdClass does not have any properties. You need to pass in $madeUpObject:

property_exists($madeUpObject, 'madeUpProperty');

The function's prototype is as follows:

bool property_exists ( mixed $class, string $property )

The $class parameter must be the "class name or an object of the class". The $property must be the name of the property.

Gronseth answered 1/2, 2013 at 21:9 Comment(2)
So madeUpObject is an instance of class madeUpObject?Expiratory
No it's an instance of stdClass.Mawson
O
2

Unless you're concerned about NULL values, you can keep it simple with isset.

Ovoviviparous answered 1/2, 2013 at 21:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.