Introspection

Introspection is the ability of a program to examine an object’s characteristics, such as its name, parent class (if any), properties, and methods. With introspection, you can write code that operates on any class or object. You don’t need to know which methods or properties are defined when you write your code; instead, you can discover that information at runtime, which makes it possible for you to write generic debuggers, serializers, profilers, etc. In this section, we look at the introspective functions provided by PHP.

Examining Classes

To determine whether a class exists, use the class_exists() function, which takes in a string and returns a Boolean value. Alternately, you can use the get_declared_classes() function, which returns an array of defined classes and checks if the class name is in the returned array:

$doesClassExist = class_exists(classname);

$classes = get_declared_classes();
$doesClassExist = in_array(classname, $classes);

You can get the methods and properties that exist in a class (including those that are inherited from superclasses) using the get_class_methods() and get_class_vars() functions. These functions take a class name and return an array:

$methods = get_class_methods(classname);
$properties = get_class_vars(classname);

The class name can be a bare word, a quoted string, or a variable containing the class name:

$class = "Person";
$methods = get_class_methods($class);
$methods = get_class_methods(Person);     // same
$methods = get_class_methods ...

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.