"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Check if a Property Exists in a PHP Object?

How to Check if a Property Exists in a PHP Object?

Published on 2024-11-10
Browse:720

 How to Check if a Property Exists in a PHP Object?

Determining Property Existence in PHP

Unlike JavaScript, PHP does not inherently possess pure object variables. However, ascertaining whether a property exists within an object or class is possible using various approaches.

property_exists() Method

The property_exists() function allows for explicit checks on property existence. Its syntax is:

if (property_exists($ob, 'a'))

where $ob is the object or class instance.

isset() Method

Alternatively, isset() can verify if a property is set within an object. However, it's crucial to note that isset() returns false if the property's value is null.

if (isset($ob->a))

Here's an example demonstrating the differences:

$ob->a = null;
var_dump(isset($ob->a)); // false

Even though the property exists, isset() returns false due to the null value.

class Foo
{
   public $bar = null;
}

$foo = new Foo();

var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false

In this scenario, property_exists() returns true since the property is defined, while isset() returns false because the value is null.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3