Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

ตรวจสอบว่าคุณสมบัติมีอยู่ในวัตถุหรือคลาสด้วย PHP


สามารถใช้ฟังก์ชัน property_exists() หรือ isset() เพื่อตรวจสอบว่าคุณสมบัตินั้นมีอยู่ในคลาสหรืออ็อบเจกต์หรือไม่

ไวยากรณ์

ด้านล่างเป็นไวยากรณ์ของ property_exists() function−

property_exists( mixed $class , string $property )

ตัวอย่าง

if (property_exists($object, 'a_property'))

ด้านล่างนี้คือไวยากรณ์ของฟังก์ชัน isset()−

isset( mixed $var [, mixed $... ] )

ตัวอย่าง

if (isset($object->a_property))

isset() จะคืนค่าเท็จหาก 'a_property' เป็นค่าว่าง

ตัวอย่าง

เรามาดูตัวอย่างกัน −

<?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)