What is PHP property_exists() Function?
If you want to check whether a property exists in an object or in a class, use property_exists() function.
Syntax:
property_exists(object_or_class, property_name)
Parameters:
The Function has 2 parameters which are required-
object_or_class (Required): It specifies the name of the object or the class.
property_name (Required): It specifies the name of the property.
Return Values:
The function returns-
- TRUE – if the property exists
- FALSE – if the property doesn’t exist
Examples:
Example 1:
<?php
class Human {
public $hand = 4;
private $leg = 2;
protected $teeth = 32;
public static $tail;
}
$Exist = property_exists('Human', 'hand');
echo "Does public property 'hand' exist? " . ($Exist ? "Yes." : "No."); echo "<br />";
$Exist = property_exists('Human', 'leg');
echo "Does private property 'leg' exist? " . ($Exist ? "Yes." : "No."); echo "<br />";
$Exist = property_exists('Human', 'teeth');
echo "Does protected property 'teeth' exist? " . ($Exist ? "Yes." : "No."); echo "<br />";
$Exist = property_exists('Human', 'tail');
echo "Does public static property 'tail' exist? " . ($Exist ? "Yes." : "No."); echo "<br />";
$Exist = property_exists('Human', 'horn');
echo "Does non-exist property 'horn' exist? " . ($Exist ? "Yes." : "No."); echo "<br />";
?>
Output:
Does public property 'hand' exist? Yes.
Does private property 'leg' exist? Yes.
Does protected property 'teeth' exist? Yes.
Does public static property 'tail' exist? Yes.
Does non-exist property 'horn' exist? No.
Example 2:
<?php
class Human1 {
public $hand = 4;
private $leg = 2;
protected $teeth = 32;
public static $tail;
}
$objHuman1 = new Human1();
$Exist = property_exists($objHuman1, 'hand');
echo "Does public property 'hand' exist? " . ($Exist ? "Yes." : "No."); echo "<br />";
$Exist = property_exists($objHuman1, 'leg');
echo "Does private property 'leg' exist? " . ($Exist ? "Yes." : "No."); echo "<br />";
$Exist = property_exists($objHuman1, 'tail');
echo "Does public static property 'tail' exist? " . ($Exist ? "Yes." : "No."); echo "<br />";
$Exist = property_exists($objHuman1, 'horn');
echo "Does non-exist property 'horn' exist? " . ($Exist ? "Yes." : "No."); echo "<br />";
?>
Output:
Does public property 'hand' exist? Yes.
Does private property 'leg' exist? Yes.
Does public static property 'tail' exist? Yes.
Does non-exist property 'horn' exist? No.
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP property_exists() Function
property_exists() is a class/object type function in PHP. Use this function to check a property existence in a class or in an object.