The feature illustrated below operates on PHP values, objects, or language metadata.
What Is get_object_vars in PHP?
Returns the accessible non-static properties of an object as an associative array, based on the scope from which it is called.
get_object_vars(object $object) : array
Parameters:
$object— Required. The object being inspected or initialized.
Return type: array. The calling scope controls whether protected or private properties appear.
Example 1: Understanding the Basic Behavior
<?php
$product = (object)['name'=>'Book','price'=>25];
print_r(get_object_vars($product));
Output:
Array
(
[name] => Book
[price] => 25
)
Explanation: Returns the accessible non-static properties of an object as an associative array, based on the scope from which it is called.
Example 2: Testing Another Case
<?php
class Product { public string $name = 'Notebook'; private int $cost = 10; }
print_r(get_object_vars(new Product()));
Output:
Array
(
[name] => Notebook
)
Explanation: The calling scope controls whether protected or private properties appear.
Practical Example: Applying the Operation
<?php
$settings = new stdClass();
$settings->theme = 'dark';
$settings->language = 'en';
foreach (get_object_vars($settings) as $name => $value) { echo $name . ': ' . $value . '\n'; }
Output:
theme: dark\nlanguage: en\n
Explanation: Uninitialized typed properties are omitted; do not treat the array as a complete schema.
Important Behavior and Edge Cases
- The calling scope controls whether protected or private properties appear.
- Uninitialized typed properties are omitted; do not treat the array as a complete schema.
Comparison With Related Approaches
| Approach | When to Use It |
|---|---|
get_object_vars | Returns the accessible non-static properties of an object as an associative array, based on the scope from which it is called. |
get_mangled_object_vars() | get_mangled_object_vars() includes mangled protected/private keys; get_object_vars() follows visibility at the call site. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Expecting the method to reveal every private property from outside its class. | The calling scope controls whether protected or private properties appear. |
| Choosing get_mangled_object_vars() without checking whether it provides the same result. | get_mangled_object_vars() includes mangled protected/private keys; get_object_vars() follows visibility at the call site. |
Key Takeaways
- Returns the accessible non-static properties of an object as an associative array, based on the scope from which it is called.
- The calling scope controls whether protected or private properties appear.
- Uninitialized typed properties are omitted; do not treat the array as a complete schema.
The examples demonstrate where get_object_vars fits within php programming. Verify the relevant preconditions whenever you adapt the code to real data.