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?

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319

3 Answers3

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 
nickb
  • 59,313
  • 13
  • 108
  • 143
  • So $madeUpObject is an instance of class madeUpObject ? – Koray Tugay Feb 01 '13 at 21:12
  • 1
    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. – nickb Feb 01 '13 at 21:14
  • Interesting. So the class does not have the field, but the object does.. Thanks. – Koray Tugay Feb 01 '13 at 21:15
  • I came to this article just to realize that I have been using the call arguments in the wrong order! – Adam Fowler Jan 26 '17 at 21:34
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.

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
2

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

Martin
  • 6,632
  • 4
  • 25
  • 28