Laravel,方法 [...] 不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38860429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel, Method [...] does not exist
提问by DomainFlag
I have the controller:
我有控制器:
class Comments extends Controller
{
public function GenerateComments($id)
{
$theme = DB::table('New_Themes')
->where('id', $id)
->get();
$Comments = NewTheme_Comment::where('id_theme', $id)->get();
$array = $this->tree($Comments);
function tree($Comments, $parent_id = 0, $level=0, $c=0)
{
global $var;
global $array;
global $m;
foreach($Comments as $Comment)
{
if ($Comment['parent_id'] == $parent_id) {
$m++;
$array[$m][0]=$Comment['id'];
If ($level > $var) {$var++; $array[$m][1]=0;} else {
if ($c < 0) $array[$m][1]=$var-$level+1; else {$c--; $array[$m][1]=0;};
$var=$level;
};
tree($Comments, $Comment['id'], $level+1,$c);
}
};
return $this->$array;
};
return view('comments', ['Themes'=> $theme, 'Comments'=> $Comments, 'Array' => $array]);
}
The problem is
问题是
Method [tree] does not exist.
方法 [tree] 不存在。
but I don't understand why it appears, if I am calling a function within a function (like that below)
但我不明白为什么会出现,如果我在一个函数中调用一个函数(如下所示)
$array = $this->tree($Comments);
function tree($Comments, $parent_id = 0, $level=0, $c=0)
{
return $this->$array;
}
Are there any ideas why this isn't working?
有什么想法为什么这不起作用?
回答by Zayn Ali
You are calling your function tree
with $this
which means PHP will look tree
as a method inside Comments
class instead of your GenerateComments
method.
您正在调用您的函数tree
,$this
这意味着 PHP 将看起来tree
像是Comments
类中的GenerateComments
方法而不是您的方法。
Change
改变
$array = $this->tree($Comments);
To this
对此
$array = tree($Comments);
Note:You are also defining your function after you are calling it. PHP will look tree
as it is in the namespace so it'll either won't work. Instead just define your function before you call it. Like so
注意:在调用函数之后,您也在定义函数。PHP 看起来tree
就像它在命名空间中一样,所以它要么不会工作。而是在调用之前定义您的函数。像这样
function tree($Comments, $parent_id = 0, $level = 0, $c = 0) {
// ...
}
$array = tree($Comments);
It is also not recommendedto define your function inside of a function. Instead doing that, just make your tree
function a method
inside your controller and use that instead. Like so
它也建议不要定义一个函数中的功能。而不是这样做,只需将您的tree
功能a method
放在您的控制器中并使用它。像这样
class Comments extends Controller
{
public function GenerateComments()
{
// ...
$array = $this->tree($comments);
}
public function tree($tree)
{
// ...
}
}
回答by Jose Rojas
Try calling the function with call_user_func
this way:
尝试用call_user_func
这种方式调用函数:
$array = call_user_func('tree', $Comments);
回答by thinice
Your tree
function is inside the controller GenerateComments
function.
您的tree
功能在控制器GenerateComments
功能内。
It appears you want to use it as a class method.
看来您想将其用作类方法。