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
.)
Each of these classes have a function called OnCall()
.
How can I create an instance of every class in my directory and execute all of their OnCall()
s?
I cannot do it manually ($sample = new Sample(); $sample->OnCall();
, etc etc etc) because more classes will be added, edited and deleted by users.
This is an old question, but I think this is a better solution.
Just by doing:
use Symfony\Component\ClassLoader\ClassMapGenerator;
var_dump(ClassMapGenerator::createMap(__DIR__.'/library'));
You get:
Array
(
[Acme\Foo] => /var/www/library/foo/Bar.php
[Acme\Foo\Bar] => /var/www/library/foo/bar/Foo.php
[Acme\Bar\Baz] => /var/www/library/bar/baz/Boo.php
[Acme\Bar] => /var/www/library/bar/Foo.php
)
(taken from the documentation)
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();
}
}
Since the Symfony ClassLoader component is deprecated, you can use ClassMapGenerator
from Composer.
You need first to add the Composer package with:
composer require composer/class-map-generator
Then you can use:
$map = ClassMapGenerator::createMap(__DIR__ . '/mydirectory');
You will get the related associative table with fully qualified name and file path.
You make a custom loop with in directory and take all required filenames then make something like this.
if $filename = your filename
require_once $filename;
$className = basename($filename, ".php");
$class = new $className;
$class->OnCall();
Another solution is to store all required filenames in array and then loop its array.
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