build a class programmatically from Files and curr

2019-12-16 20:16发布

问题:

A. i have this multiple files with methods inside it like this:

file1.php
    <?php
    function Example1() {
        echo 'Example1';
    }
    function Example2() {
        echo 'Example1';
    }
    ?>

B. and this other:

file2.php
    <?php
    function Example3() {
        echo 'Example1';
    }
    function Example4() {
        echo 'Example1';
    }
    ?>

C. and i want to associate this to a class but i need make it programmatically:

class Class_Example {
    public function ChargeFunction() {
        $DirectoryToScan ='/functionsfiles/'
        $ABS = scandir(DirectoryToScan, 1);
        $FunctionFiles=[];
        foreach ($ABS as $key => $name) {
            if (strpos($name, 'class.') !== false) {
                $FunctionFiles[$name] = DirectoryToScan . $name;
            }
        }
        foreach (FunctionFiles as $key => $functionfile) {
            require_once $functionfile;
        }
        //all methods can be used on here.
    }
}

D. i cant use, is that i want:

$intance = new Class_Example();
$intance->Example1();
$intance->Example2();

How can I associate the files with methods to a class, without changing the structure or content on file methods??

回答1:

i solve it with this code:

class Class_Example {
    public function ChargeFunction() {
        $DirectoryToScan ='/functionsfiles/'
        $ABS = scandir(DirectoryToScan, 1);
        $FunctionFiles=[];
        foreach ($ABS as $key => $name) {
            if (strpos($name, 'class.') !== false) {
                $FunctionFiles[$name] = DirectoryToScan . $name;
            }
        }
        foreach ($FunctionFiles as $key => $functionfile) {
            require_once $functionfile;
        }
    }
    function __call($functionName, $args) {
        if (function_exists($functionName)) {
            return call_user_func_array($functionName, $args);
        }
    }
}

implement the magic function __call to solve this.