Search code examples
phpintrospection

Get Name of Most Recent Class Declaration?


I know this might be a long shot, but I am hoping that this is possible. This is not really a stumbling block in the project I am developing (though it could really help), but I am curious.

I want to get the name of the class being declared most recently. Basically, I have a piece of code that I need to append right after certain files containing declarations of certain (not all) classes. This piece of code is repeating, except for the class being initiated in it.

I have tried get_declared_classes() but the array is sorted alphabetically, and not in the sequence of when the classes are declared.

Here is a sample code of what I am trying to achieve:

class MyClass{

}

//Repeating code:

if(isset($_REQUEST['fxn'])){

    $class = new MyClass(); //I am hoping to make the class name dynamic, according to the most recent declared class...

    //More repeating codes here...
}

(It would save much time during development and in the future while maintaining if I could just use include to append this piece of code wherever it is needed. Hence my question.)


Solution

  • You could probably grab the last element returned by get_declared_classes, but something seems terribly, terribly wrong if you are trying to do this. Perhaps you could better explain your situation for more perspective on other ways to accomplish your goal.