Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 output is:

abc does not exist

So why does this not work?

like image 788
Koray Tugay Avatar asked Feb 01 '13 21:02

Koray Tugay


3 Answers

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 
like image 173
nickb Avatar answered Nov 09 '22 17:11

nickb


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.

like image 39
Sverri M. Olsen Avatar answered Nov 09 '22 17:11

Sverri M. Olsen


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

like image 26
Martin Avatar answered Nov 09 '22 16:11

Martin