get_object_vars
Returns the accessible properties of an object as an array.
Syntax
get_object_vars(object $object): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $object | object | The object. |
Return value
arrayAn array of property names and values.
Examples
Only public properties are visible from outside:
<?php
class User
{
public string $name = 'Anna';
private string $password = 'secret';
public function all(): array
{
return get_object_vars($this);
}
}
$user = new User();
echo json_encode(get_object_vars($user)), "\n";
echo json_encode($user->all());Output:
{"name":"Anna"}
{"name":"Anna","password":"secret"}Notes
The result depends on where it is called: inside the class the function returns private properties as well.
See also
- property_exists — Checks whether a class or an object has a property.
- get_class_methods — Returns the names of a class's methods.
- json_encode — Converts a value to a JSON string.
Related recipes
In the tutorial
- Classes and objects — What classes and objects are in PHP, how to describe properties and methods and create objects.