使用PHP在目录中创建所有类的实例 [英] Create instances of all classes in a directory with PHP
问题描述
我有一个目录,其中包含几个PHP文件,这些文件由与这些文件同名的类组成。 ( Sample.php
的类将称为 Sample
。)
I have a directory with several PHP files consisting of classes with the same names as the files. (Sample.php
's class will be called Sample
.)
每个此类都有一个名为 OnCall()
的函数。
Each of these classes have a function called OnCall()
.
如何创建实例目录中每个类的名称并执行其所有 OnCall()
s?
How can I create an instance of every class in my directory and execute all of their OnCall()
s?
我无法手动执行( $ sample = new Sample(); $ sample-> OnCall();
等),因为用户会添加,编辑和删除更多的类。
I cannot do it manually ($sample = new Sample(); $sample->OnCall();
, etc etc etc) because more classes will be added, edited and deleted by users.
推荐答案
这样的东西应该会得到完成的工作:
Something like this ought to get the job done:
<?php
foreach (glob('test/class/*.php') as $file)
{
require_once $file;
// get the file name of the current file without the extension
// which is essentially the class name
$class = basename($file, '.php');
if (class_exists($class))
{
$obj = new $class;
$obj->OnCall();
}
}
这篇关于使用PHP在目录中创建所有类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!