2012-09-24 145 views
1

我想自動加載函數,而不是類。錯誤:PHP自動加載功能

PHP Fatal error: Cannot redeclare proba() (previously declared in /var/www/localhost/proba-function.php:5) in /var/www/localhost/proba-function.php on line 7

在index.php代碼:

class ASD { 
    function __construct() { 
     self::proba(); 
    } 

    public static function __callStatic ($name, $arguments) { 
     $foo = false; 
     $directories = array_diff (scandir (__DIR__), array ('..')); 

     foreach ($directories as $directory) { 
      $directory = __DIR__ . DIRECTORY_SEPARATOR . $directory; 
      if (is_dir ($directory)) { 
       $file = $directory . DIRECTORY_SEPARATOR . strtolower ($name) . '-function.php'; 
       if (file_exists ($file)) { 
        include ($file); // It's ok. 
        if (function_exists ($name)) { 
         $foo = true; 
         call_user_func_array(array('ASD', $name), $arguments); // It's not work. 
         break; 
        } else {} 
       } else {} 
      } else {} 
     } 

     if ($foo === FALSE) { 
      $this -> error (NULL, $name); 
     } else {} 
    } 
} 

的PROBA-function.php:

function proba() { 
    print 'foo'; 
} 
+0

除了去除空'else'聲明,我也前'call_user_func_array'添加一個'return'語句,這樣你可以得到你的函數的返回值,並移除'突破' – adlawson

回答

6

嘗試用include_once()更換您的通話include(),使相同的文件不會包含多次。

爲了確保該文件實際包含在內,也許可以考慮使用require_once()而不是簡單的include_once()

也請參閱該文檔:http://php.net/manual/en/function.include.php

+2

甚至可能是'require_once',因爲這些函數似乎對應用程序至關重要。 – Yuriy

+0

好的建議!剛剛更新了我的答案=) –