Sling Academy
Home/PHP/PHP: How to List All Properties and Methods of an Object

PHP: How to List All Properties and Methods of an Object

Last updated: January 10, 2024

Overview

In PHP, objects are instances of classes which have properties and methods. At times, it’s necessary to inspect these elements, especially during debugging or dynamic processing. This guide explains how to list all properties and methods of an object in PHP, utilizing built-in functions and Reflection.

Using get_object_vars() and get_class_methods()

For a quick and easy way to list properties and methods, PHP offers two functions: get_object_vars() and get_class_methods().

$obj = new MyClass();
$properties = get_object_vars($obj);
print_r($properties);

$methods = get_class_methods($obj);
print_r($methods);

The get_object_vars() function returns an associative array of defined properties accessible from the current scope, while get_class_methods() provides an array of the names of the methods in the class.

Exploring the Reflection Class

The PHP Reflection API provides a more sophisticated approach. The ReflectionClass class allows the extraction of detailed information about a class’s properties and methods.

$reflector = new ReflectionClass('MyClass');
$properties = $reflector->getProperties();

foreach($properties as $property) {
    echo $property->getName() . '\n';
}

$methods = $reflector->getMethods();
foreach($methods as $method) {
    echo $method->getName() . '\n';
}

This approach allows you to also retrieve information about private and protected properties and methods that are not accessible through other means.

Considering Scope with get_class_vars() and Array Filtering

To include only those properties that are publicly accessible, use get_class_vars(). You can also combine array filtering functions to fine-tune the results based on specific criteria.

$publicProperties = get_class_vars('MyClass');
print_r($publicProperties);

$privateProperties = array_filter(
    get_object_vars($obj),
    function($key) use ($publicProperties) {
        return !array_key_exists($key, $publicProperties);
    },
    ARRAY_FILTER_USE_KEY
);
print_r($privateProperties);

The above snippet first obtains the public properties, and then filters the full property list to exclude those, yielding private properties.

Advanced Reflection: Property and Method Visibility

For more advanced scenarios, you may need to inspect the visibility of properties and methods. The ReflectionProperty and ReflectionMethod classes have methods like isPrivate(), isProtected(), and isPublic().

// Inspecting property visibility
foreach($properties as $property) {
    if ($property->isPrivate()) {
        echo 'Private property: ' . $property->getName() . '\n';
    }
}

// Inspecting method visibility
foreach($methods as $method) {
    if ($method->isProtected()) {
        echo 'Protected method: ' . $method->getName() . '\n';
    }
}

This advanced level of reflection is particularly important for building frameworks or complex systems that rely on class behaviors.

Dealing with Inherited and Trait Properties and Methods

Objects can also inherit properties and methods or use traits. PHP Reflection can still handle these situations, with the ability to list inherited members and trait usages separately.

// Listing inherited properties
$parentClass = $reflector->getParentClass();
if ($parentClass) {
    $inheritedProperties = $parentClass->getProperties();
    // Process inherited properties as before
}

// Listing methods provided via trait
$traits = $reflector->getTraits();
foreach ($traits as $trait) {
    $traitMethods = $trait->getMethods();
    // Process trait methods as before
}

This way, you can distinguish between original properties/methods and those acquired from parent classes or traits.

Conclusion

In PHP, understanding how to list an object’s properties and methods is essential for introspection and meta-programming. This guide has touched on basic functions like get_object_vars() and get_class_methods(), as well as delved into the more complex features of the Reflection API. With these tools, developers are well-equipped to examine and manipulate object details tailored to their specific needs.

Next Article: How to compare 2 objects in PHP

Previous Article: How to merge 2 objects in PHP

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array