Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

get_object_vars

Returns the accessible properties of an object as an array.

Syntax

get_object_vars(object $object): array

Parameters

ParameterTypeDescription
$objectobjectThe 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

Related recipes

In the tutorial

  • Classes and objects — What classes and objects are in PHP, how to describe properties and methods and create objects.

Thanks for reading!

Donate to the site — we work hard for you.