Startup functions in php

Is it possible to autoload functions?

What I have, I wrote functions distributed across different files named after the function name, so I need to automatically download the file containing this function. Is there any way to do this?

+3
function php
Nov 16 '10 at 17:10
source share
5 answers

You can autoload classes , so if you create your functions static class methods , then it will work.

abstract class Util { static function doSomething() { } } 

Using:

 Util::doSomething(); 
+5
Nov 16 '10 at 17:14
source share
+2
Nov 16 '10 at 17:13
source share

No, but you can load classes. using __autoload($className)

+1
Nov 16 '10 at 17:14
source share

Although not reasonable, it is possible.

You can save these functions in a file and add this file to all requested scripts:

  • front controller template (one central file for all requests, include it there)
  • php auto_prepend_file

But a reasonable OOP solution would be to combine these functions into classes and use __autoload or some framework autoloader like Zend_Autloader to speed up and load only those functions that you need.

0
Nov 16 '10 at 20:41
source share

Not directly. But you can add the following code at the beginning of your code to automatically include functions:

 call_user_func(function($p,$w){$c=file_get_contents(__FILE__);$fs=explode('(',$c);$f=[];for($i=65;$i<=90;$i++){$vc[chr($i)]=1;$vc[chr($i+32)]=1;if($i<75)$vc[chr($i-17)]=1;}$vc['_']=1;foreach($fs as $fn){$fn=rtrim($fn);for($i=strlen($fn)-1;$i>=0;$i--){if(!isset($vc[$fn[$i]])){$f[]=substr($fn,$i+1);break;}}}foreach($f as $c){@include_once($p.$w[0].$c.$w[1]);}}, "func_dir/",["func_",".php"]); 

The only thing you need to change is the second line: The first parameter is a folder to search for files, the second parameter is an array that wraps both values ​​around the function name.

For example: if your function files are located in the subdirectory "func_dir /" and are namen "func _ *. Php" (where * is the name of the function), you can use the above code directly as is. However, you must put this code in every file where you want to automatically load functions and adapt the path.

It is a little dirty, but it works. Hope my code helps you.

0
Aug 30 '15 at 17:58
source share



All Articles