Cover by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required