PHP - 類/物件 get_object_vars() 函式



PHP 類/物件 get_object_vars() 函式用於以陣列的形式獲取物件的屬性。此函式對於檢視或管理物件的屬性很有用。它還可以訪問物件的非靜態屬性。

語法

以下是 PHP 類/物件 get_object_vars() 函式的語法:

array get_object_vars(object $object)

引數

此函式接受 $object 引數,它是您要檢索其屬性的物件。

返回值

get_object_vars() 函式返回一個關聯陣列,其中包含作用域內物件的可訪問的非靜態屬性。

PHP 版本

get_object_vars() 函式最初在 PHP 4 核心版本中引入,並且在 PHP 5、PHP 7 和 PHP 8 中都能輕鬆使用。

示例 1

首先,我們將向您展示 PHP 類/物件 get_object_vars() 函式的基本示例,以獲取簡單物件的屬性。

<?php
   // Create a Person class
   class Person {
      public $name = "Aman";
      public $age = 25;
   }
  
   // Create object of the class
   $person = new Person();

   // Get the properties
   $properties = get_object_vars($person);

   // Display the result
   print_r($properties);
?>

輸出

以下是以下程式碼的結果:

Array
(
    [name] => Aman
    [age] => 25
)

示例 2

在下面的 PHP 程式碼中,我們將建立一個類,並在類中包含公共和私有屬性。因此,使用 get_object_vars() 函式只會返回公共屬性。

<?php
   // Create a Person class
   class Car {
      public $make = "Volkswagen";
      private $model = "Sedans";
   }
   // Create object of the class
   $car = new Car();

   // Get the properties
   $properties = get_object_vars($car);
  
   // Display the result
   print_r($properties);
?> 

輸出

這將生成以下輸出:

Array
(
    [make] => Volkswagen
)

示例 3

此示例使用 get_object_vars() 函式和自定義類來表示二維點。該函式在新增新屬性之前和之後返回物件屬性的關聯陣列。

<?php
   // Create a class
   class Coordinate2D {
      var $a, $b;
      var $description;
      
      function Coordinate2D($a, $b) {
         $this->a = $a;
         $this->b = $b;
      }
      
      function setDescription($description) {
         $this->description = $description;
      }
      
      function getCoordinates() {
         return array("a" => $this->a, "b" => $this->b, "description" => $this->description);
      }
   }
   
   $point = new Coordinate2D(1.233, 3.445);
   print_r(get_object_vars($point));
   
   $point->setDescription("Location A");
   print_r(get_object_vars($point));
?> 

輸出

這將建立以下輸出:

Array
(
    [a] => 
    [b] => 
    [description] => 
)
Array
(
    [a] => 
    [b] => 
    [description] => Location A
)
php_function_reference.htm
廣告