使用字符串名称调用静态类的方法



在路由器/web.php中:

Route::get('/{page}/{id}/{seo_title}', "Router@get");

在作为控制器的路由器类中:

public function get($page,$id,$seo_title)
{
$view_arg = null;
if($id)
{
$model =  "tbl_$page"."s";
$view_arg =  $model::whereId($id)->first();  
//  Error: Class 'tbl_posts' not found 
//$view_arg =  call_user_func(array($model, 'whereId'),$id)->first(); 
// Error : call_user_func() expects parameter 1 to be a valid callback, class 'tbl_posts' not found 
}
// Some other codes...
}

我得到了错误:

错误:找不到类"tbl_posts">

在以下行:

$view_arg =  $model::whereId($id)->first();  

虽然以下代码运行良好:

tbl_posts::whereId($id)->first(); 

我也尝试过以下方法:

$view_arg =  call_user_func(array($model, 'whereId'),$id)->first(); 

它给了我错误

错误:call_user_func((要求参数1是有效的回调,类

您可以在函数中直接调用Model class。

public function get($page,$id,$seo_title)
{
$view_arg = null;
if($id)
{
$model =  "App\" . "tbl_$page"."s"; 
$view_arg =  $model::whereId($id)->first();  
}
}

最新更新