Why can't I call property_exists on stdClass?

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 result:

<strong> but does not exist

So why is this not working?

+5
source share
3 answers

Try:

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

Setting the class name (and not the object, as I did) means in the definition stdClass, you need to define the property.

You can see from this demo that it prints:

abc
exists 
+11
source

Because it stdClasshas no properties. You must pass $madeUpObject:

property_exists($madeUpObject, 'madeUpProperty');

The prototype of the function is as follows:

bool property_exists ( mixed $class, string $property )

The parameter $classmust be "class name or class object ". $propertymust be the name of the property.

+4

NULL, isset.

+2

All Articles