skip to Main Content

Is there a possibility of including all functions within directory within a class. For example:

class.php

class all_functions{
 foreach(glob(__DIR__.'/functions/*.php') as $file){include($file);}
}

functions/function1.php

function hello(){
 echo 'hello';
}

functions/function2.php

function goodbye(){
 echo 'goodbye';
}

Result would be a class all_functions() that includes functions hello() and goodbye(). I’d like to just add functions into a class by just adding a file with the function.

2

Answers


  1. Chosen as BEST ANSWER

    I found a great solution to this problem. Considering everything that was mentioned in the comments, I've devised a solution. Although it deviates from the initial premise, this is a solution I was looking for:

    class.php

    class all_functions{
     function __call($method,$arguments){
      include 'functions/'.$method.'.php';
      echo $word;
     }
    }
    

    functions/hello.php

    $word='hello';
    

    functions/goodbye.php

    $word='goodbye';
    

  2. I used to have something similar. Generating JS api file on the fly according to php functions. On every request (on dev environment only) I would regenerate it and rewrite the file if necessary.

    So, here’s pseudo code:

    if (DEV) {
        $content = 'class AllFunctions {';
        
        foreach (glob(__DIR__.'/functions/*.php') as $file) {
            $functionContent = file_get_contents($file);
            $content .= "public static $functionContentnn";
        }
        
        $content .= '}';
        
        file_put_contents("AllFunctions.php", $content);
    }
    
    // later:
    include ("AllFunctions.php");
    
    AllFunctions::hello();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search