Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP 5.x, how can I detect if a class is abstract or not at run time?

Tags:

I'm looping through an array of class names in PHP, fetched via get_declared_classes().

How can I check each class name to detect whether or not that particular class is an abstract class or not?

like image 918
Keith Palmer Jr. Avatar asked Mar 20 '09 15:03

Keith Palmer Jr.


People also ask

Does PHP have abstract classes?

Class Abstraction ¶PHP has abstract classes and methods. Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature; they cannot define the implementation.

Where do we use abstract class in PHP?

We use abstract classes when we want to commit the programmer (either oneself or someone else) to write a certain class method, but we are only sure about the name of the method, and not the details of how it should be written. To take an example, circles, rectangles, octagons, etc.

What is the difference between abstract class and interface in PHP?

Interface are similar to abstract classes. The difference between interfaces and abstract classes are: Interfaces cannot have properties, while abstract classes can. All interface methods must be public, while abstract class methods is public or protected.


1 Answers

Use reflection. ReflectionClass->isAbstract()

Use it like this:

$class = new ReflectionClass('NameOfTheClass'); $abstract = $class->isAbstract(); 
like image 143
vartec Avatar answered Sep 30 '22 11:09

vartec