The get_object_vars Function

The get_object_vars function returns an associative array containing the properties of the passed object. In the returned array, the keys will be the property names, and the values will be the corresponding values of these properties. The function takes one parameter - the object whose properties need to be obtained.

Syntax

phpget_object_vars(object);

Example

Get properties of a simple object:

php<?php
  class MyClass {
    public $a = 1;
    public $b = 2;
    private $c = 3;
  }
  
  $obj = new MyClass();
  $res = get_object_vars($obj);
  print_r($res);
?>

Code execution result:

php['a' => 1, 'b' => 2]

Example

The function does not return private and protected properties:

php<?php
  class Test {
    public $x = 10;
    protected $y = 20;
    private $z = 30;
  }
  
  $test = new Test();
  $res = get_object_vars($test);
  print_r($res);
?>

Code execution result:

php['x' => 10]

Example

Working with dynamic properties:

php<?php
  $user = new stdClass();
  $user->name = 'John';
  $user->age = 25;
  
  $res = get_object_vars($user);
  print_r($res);
?>

Code execution result:

php['name' => 'John', 'age' => 25]

See Also