What is PHP get_object_vars() Function?
If you want to get the properties of an object, use PHP get_object_vars() function. You’ll come to know the name and value of each variable.
Syntax:
get_object_vars(object_name)
Parameters:
The Function has 1 parameter which is required-
object_name (Required): It specifies an object name. (Check example 1).
Return Values:
The function returns an associative array whose keys are variable names and their values are the values of the variables.
Examples:
Example 1:
<pre>
<?php
class Human {
public $hand = 2;
public $leg = 2;
public $finger = 20;
}
$objHuman = new Human();
$var_names = get_class_vars(get_class($objHuman));
echo "The object '\$objHuman' has the following variables- <br />";
print_r($var_names);
?>
</pre>
Output:
The object '$objHuman' has the following variables-
Array
(
[hand] => 2
[leg] => 2
[finger] => 20
)
Notes on get_object_vars() Function:
- This function only returns public variables. So, private, protected, and static variables are not included. Check following example-
<pre>
<?php
class Human5 {
public $hand = 2;
private $legs = 2;
protected $tail = "No";
public $eye = 2;
public static $nose = 1;
}
$objHuman = new Human5();
$var_names = get_object_vars($objHuman);
echo "The object '\$objHuman' has the following variables- <br />";
print_r($var_names);
?>
</pre>
Output:
The class 'Human' has the following variables-
The object '$objHuman' has the following variables-
Array
(
[hand] => 2
[eye] => 2
)
<pre>
<?php
class Human3 {
function __construct(){
$this -> hand = 4;
}
public $hand = 2;
public $leg = 2;
public $finger = 20;
}
$objHuman = new Human3();
$var_names = get_object_vars($objHuman);
echo "The object '\$objHuman' has the following variables- <br />";
print_r($var_names);
?>
</pre>
Output:
The object '$objHuman' has the following variables-
Array
(
[hand] => 4
[leg] => 2
[finger] => 20
)
<pre>
<?php
class Human4 {
public $hand = 2;
public $leg = 2;
public $finger = 20;
}
$objHuman = new Human4();
$objHuman-> hand = 3;
$var_names = get_object_vars($objHuman);
echo "The object '\$objHuman' has the following variables- <br />";
print_r($var_names);
?>
</pre>
Output:
The object '$objHuman' has the following variables-
Array
(
[hand] => 3
[leg] => 2
[finger] => 20
)
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP get_object_vars() Function
get_object_vars() is a class/object type function in PHP. It is a useful function to see the list of variables an object contains.