简体   繁体   中英

PHP & Retrospection How to retrospect without knowing class in advance

I want to use Retrospection to call specific functions on a class that I don't know.

I have a directory where PHP files are stored. I have another directory where my current PHP class is stored like:

C:/ PHP-dir
      |
      ---FilesDir
      |    |
      |    ----SomeClass.php
      |    ----OtherClass.php
      |
      ---MyProgDir
           |
           ----MyClassWithRetrospection.php

In MyClassWithRetrospection I read all files from FilesDir, I strip the '.php'from the filename and use the resulting string as a Class name.

So if I do a "new RetrospectionClass('SomeClass');" I get an exception telling me it can't find SomeClass in the directory where MyClassWithRetrospection is located. Duh, I know that.

As I don't know which classes are in the FilesDir I can't do an include/required in my MyClassWithRetrospection.php file.

So does anyone know how to make the content of the FilesDir directory available at runtime?

Regards, Werner

You need to just include it at runtime, which means you have to follow a convention for naming your files, or you have to have a huge array of where each file is located. Assuming SomeClass.php contains a class called SomeClass, when you do

new RetrospectionClass($className);

You would first do

include_once '../FilesDir/'.$className.'.php'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM