315 of 410 menu

The property_exists Function

The property_exists function checks if the specified property exists in the given object or class. The first parameter accepts an object or a class name, and the second one - the name of the property to check. The function returns true if the property exists, and false otherwise.

Syntax

property_exists(object|string $object_or_class, string $property): bool

Example

Let's check for the existence of a property in an object:

<?php class MyClass { public $prop1 = 'value'; } $obj = new MyClass(); $res = property_exists($obj, 'prop1'); var_dump($res); ?>

Code execution result:

true

Example

Let's check for the existence of a non-existent property:

<?php class MyClass { public $prop1 = 'value'; } $obj = new MyClass(); $res = property_exists($obj, 'prop2'); var_dump($res); ?>

Code execution result:

false

Example

Let's check for the existence of a property in a class (without creating an object):

<?php class MyClass { public $prop1 = 'value'; } $res = property_exists('MyClass', 'prop1'); var_dump($res); ?>

Code execution result:

true

Example

Let's check for the existence of a protected property:

<?php class MyClass { protected $prop1 = 'value'; } $obj = new MyClass(); $res = property_exists($obj, 'prop1'); var_dump($res); ?>

Code execution result:

true

See Also

byenru