使用 PHP 檢查屬性是否存在於物件或類中
property_exists() 或 isset() 函式可用於檢查屬性是否存在於類或物件中。
語法
以下是 property_exists() 函式的語法−
property_exists( mixed $class , string $property )
示例
if (property_exists($object, 'a_property'))
以下是 isset() 函式的語法−
isset( mixed $var [, mixed $... ] )
示例
if (isset($object->a_property))
如果 ‘a_property’ 為 null,則 isset() 將返回 false。
示例
讓我們看一個示例−
<?php class Demo { public $one; private $two; static protected $VAL; static function VAL() { var_dump(property_exists('myClass', 'two')); } } var_dump(property_exists('Demo', 'one')); var_dump(property_exists(new Demo, 'one')); ?>
輸出
將生成以下輸出−
bool(true) bool(true)
廣告