PHP - Class/Object get_object_vars() Function
The PHP Class/Object get_object_vars() function is used to get the properties of an object in the form of an array. This function is useful for viewing or managing properties of an object. It also offers to use an object's non-static properties.
Syntax
Here is the syntax of the PHP Class/Object get_object_vars() function −
array get_object_vars(object $object)
Parameters
This function accepts $object parameter which is the object whose properties you want to retrieve.
Return Value
The get_object_vars() function returns an associative array of defined object-accessible non-static properties for the object in scope.
PHP Version
First introduced in core PHP 4, the get_object_vars() function continues to function easily in PHP 5, PHP 7, and PHP 8.
Example 1
First we will show you the basic example of the PHP Class/Object get_object_vars() function to get the properties of a simple object.
<?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);
?>
Output
Here is the outcome of the following code −
Array
(
[name] => Aman
[age] => 25
)
Example 2
In the below PHP code we will create a class and inside the class we will have public and private properties. So using the get_object_vars() function only returns public properties.
<?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);
?>
Output
This will generate the below output −
Array
(
[make] => Volkswagen
)
Example 3
This example uses the get_object_vars() function and a custom class to represent a 2D point. The function returns an associative array of the object's properties before and after the addition of a new property.
<?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));
?>
Output
This will create the below output −
Array
(
[a] =>
[b] =>
[description] =>
)
Array
(
[a] =>
[b] =>
[description] => Location A
)