首頁  >  文章  >  後端開發  >  如何在 PHP 中檢查物件或類別屬性是否存在?

如何在 PHP 中檢查物件或類別屬性是否存在?

Patricia Arquette
Patricia Arquette原創
2024-10-28 13:59:30491瀏覽

How to Check for Object or Class Property Existence in PHP?

PHP:檢查物件或類別屬性是否存在

在PHP 中,存取物件或類別上未定義的屬性會導致致命錯誤。但是,在使用屬性之前可能需要先確定屬性是否存在。

物件屬性檢查:

為了檢查物件中屬性是否存在,PHP 提供了property_exists 函數:

<code class="php">if (property_exists($ob, 'a')) {
  // Property 'a' exists in the object
}</code>

類屬性檢查:

您也可以使用property_exists 檢查類別中的屬性:
<code class="php">if (property_exists('SomeClass', 'property')) {
  // Property 'property' exists in the class
}</code>

取代isset():

<code class="php">if (isset($ob->a)) {
  // Property 'a' exists in the object (but not necessarily set)
}</code>
另一個種選擇是在物件的屬性上使用isset():

但是,請注意isset() 將傳回false如果屬性明確設定為null。

null 屬性範例:
<code class="php">$ob->a = null;
var_dump(isset($ob->a)); // false
var_dump(property_exists($ob, 'a')); // true</code>

以上是如何在 PHP 中檢查物件或類別屬性是否存在?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn