"Call to undefined function App\Http\Controllers\ [ function name ]" 的意思是:调用未定义的函数 App\Http\Controllers\ [ 函数名 ] 。
"Call to undefined function App\Http\Controllers\ [ function name ]" 的意思是:调用未定义的函数 App\Http\Controllers\ [ 函数名 ] 。
这个问题已经有了答案:
在我的控制器中,我创建了一个函数getFactorial
public static function getFactorial($num) { $fact = 1; for($i = 1; $i <= $num ;$i++) $fact = $fact * $i; return $fact; }
然后,我像这样使用它
public function codingPuzzleProcess() { $word = strtoupper(Input::get('word')); $length = strlen($word); $max_value = ($length * 26); $characters = str_split($word); $num = 1 ; $index = 1; sort($characters); foreach ( $characters as $character) { $num += getFactorial($index) * $index; $index ++; } return Redirect::to('/coding-puzzle') ->with('word', $word ) ->with('num', $num ) ->with('success','Submit successfully!'); }
由于某种原因,我一直收到这个错误
Call to undefined function App\\Http\\Controllers\\getFactorial()
有人能教我如何解决这个错误吗?
提前感谢。
CodeController.php
<?php namespace App\Http\Controllers; use View, Input, Redirect; class CodeController extends Controller { public function codingPuzzle() { return View::make('codes.puzzle'); } public static function getFactorial($num) { $fact = 1; for($i = 1; $i <= $num ;$i++) $fact = $fact * $i; return $fact; } public function codingPuzzleProcess() { $word = strtoupper(Input::get('word')); $length = strlen($word); $max_value = ($length * 26); $characters = str_split($word); $num = 1 ; $index = 1; sort($characters); foreach ( $characters as $character) { $num += getFactorial($index) * $index; $index ++; } return Redirect::to('/coding-puzzle') ->with('word', $word ) ->with('num', $num ) ->with('success','Submit successfully!'); } }
admin 更改状态以发布 2023年5月22日
假设你在 CodeController
中定义了 static getFactorial
函数
那么这就是你需要调用静态函数的方式, 因为静态属性和方法存在于类中, 而不是使用该类创建的对象中。
CodeController::getFactorial($index);
----------------更新----------------
为了最佳实践, 我认为你可以把这种函数放在一个单独的文件中, 这样就可以更轻松地维护它们。
要做到这一点
在 app
目录下创建一个文件夹并将其命名为 lib
(你可以使用你喜欢的任意名称)。
这个文件夹需要被自动加载, 为了做到这一点, 将 app/lib
添加到 composer.json
中, 如下所示, 然后运行 composer dumpautoload
命令。
"autoload": { "classmap": [ "app/commands", "app/controllers", ............ "app/lib" ] },
然后 lib
文件夹中的文件将自动加载。
接下来在 lib
中创建一个文件, 我将其命名为 helperFunctions.php
在其中定义函数。
if ( ! function_exists('getFactorial')) { /** * return the factorial of a number * * @param $number * @return string */ function getFactorial($date) { $fact = 1; for($i = 1; $i <= $num ;$i++) $fact = $fact * $i; return $fact; } }
然后在应用程序的任何地方调用它即可。
$fatorial_value = getFactorial(225);