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.
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
declared_classes() function, which returns an
array of defined classes and checks if the class name is in the
$doesClassExist = class_exists(
classname); $classes = get_declared_classes(); $doesClassExist = in_array(
You can get the methods and properties that exist in a class
(including those that are inherited from superclasses) using the
get_class_vars() functions. These functions
take a class name and return an array:
$methods = get_class_methods(
classname); $properties = get_class_vars(
The class name can be a bare word, a quoted string, or a variable containing the class name: