Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining what classes are defined in a PHP class file

Tags:

php

class

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.

like image 558
Allain Lalonde Avatar asked May 30 '09 03:05

Allain Lalonde


People also ask

How do you define a class in PHP explain in detail about classes?

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.

How a class is declared in PHP?

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]*$ .

How do I find the instance of an object in PHP?

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

Are there classes in PHP?

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.


1 Answers

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; } 
like image 181
Venkat D. Avatar answered Oct 13 '22 22:10

Venkat D.