Given that each PHP file in our project contains a single class definition, how can I determine what class or classes are defined within the file?
I know I could just regex the file for class
statements, but I'd prefer to do something that's more efficient.
Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values. Objects of a class is created using the new keyword.
The class name can be any valid label, provided it is not a PHP reserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$ .
$var instanceof TestClass: The operator “instanceof” returns true if the variable $var is an object of the specified class (here is: “TestClass”). get_class($var): Returns the name of the class from $var, which can be compared with the desired class name. is_object($var): Checks whether the variable $var is an object.
PHP Classes are the means to implement Object Oriented Programming in PHP. Classes are programming language structures that define what class objects include in terms of data stored in variables also known as properties, and behavior of the objects defined by functions also known as methods.
I needed something like this for a project I am working on, and here are the functions I wrote:
function file_get_php_classes($filepath) { $php_code = file_get_contents($filepath); $classes = get_php_classes($php_code); return $classes; } function get_php_classes($php_code) { $classes = array(); $tokens = token_get_all($php_code); $count = count($tokens); for ($i = 2; $i < $count; $i++) { if ( $tokens[$i - 2][0] == T_CLASS && $tokens[$i - 1][0] == T_WHITESPACE && $tokens[$i][0] == T_STRING) { $class_name = $tokens[$i][1]; $classes[] = $class_name; } } return $classes; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With