Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create instances of all classes in a directory with PHP

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.

like image 616
James Avatar asked Feb 04 '14 18:02

James


4 Answers

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)

like image 125
amcastror Avatar answered Nov 10 '22 15:11

amcastror


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();
        }
    }
like image 42
Mark Avatar answered Nov 10 '22 13:11

Mark


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.

like image 5
Kwadz Avatar answered Nov 10 '22 13:11

Kwadz


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.

like image 1
Bright Sun Avatar answered Nov 10 '22 13:11

Bright Sun