Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

get_object_vars()

get_object_vars() is a PHP native function, which returns an array with the object properties as index, and their related respective values.

get_object_vars() does not return static properties, which are class level, and not object level.

get_object_vars() does not return uninitialized properties. It returns all existing properties, may they be specified in the class definition, or not. It returns the trait and the parent properties.

get_object_vars() respect visibility, so its result may differ depending on its calling location: private properties are only visible when get_object_vars() is called from within the class itself; protected may be visible when called from a child; otherwise, only public properties are returned.

Constants are not returned by that function.

get_object_vars() is very similar to the (array) cast operator. It is very different from the get_class_vars() method, which returns the properties as defined in the class, and including the static properties. It is also possible to use json_encode() followed by json_decode(), though some data might get lost in the translation process.

<?php

trait HasTusks {
    public $tuskLength = '3';
}

class Elephpant {
    use HasTusks;

    private int $age = 1;
    private int $weight = 2;
    public int $trunkLength = 3;
    public int $earSize = 4;
    public int $herdSize;

    static string $species = 'abc';

    function __construct() {
        unset($this->earSize);

        $this->waterIntake = 6;
    }
}

print_r(get_object_vars(new elephpant));

/**
Array
(
    [trunkLength] => 3
    [tuskLength] => 3
    [waterIntake] => 6
)
*/
?>

Documentation

See Also