【问题标题】:Call method of static class with string name使用字符串名称调用静态类的方法
【发布时间】:2020-04-04 06:33:13
【问题描述】:

在路由器/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 是有效的 回调,类

【问题讨论】:

  • tbl_posts 在命名空间中吗?
  • 不,这是一个类(模型)
  • 在字符串变量中传递模型调用的完整路径。 $model = App\Posts 然后$view_arg = $model::whereId($id)->first();
  • 要检查一下,你能显示echo tbl_posts::class;给出的内容吗?
  • 你必须use Model 类。

标签: php laravel


【解决方案1】:

您可以在函数中直接调用您的模型类。

public function get($page,$id,$seo_title)
{
    $view_arg = null;
    if($id)
    {
       $model =  "App\\" . "tbl_$page"."s"; 

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

    }
}

【讨论】:

  • tbl_posts 是我的模型名称,而不是 Post。我添加了 {use App\tbl_posts;}
  • 正如我之前提到的,当我直接使用类时它工作得很好。 {tbl_posts::whereId($id)->first();} 工作正常。
  • 对不起,第一种方法不起作用。在我的回答中使用第二种方法。
  • @Deepak 第一种方法有效。但它没有动态use。我喜欢第二种方式,但使用双引号时需要添加双反斜杠。
  • 谢谢,它成功了。但是你在“或”之前所说的是废话,因为正如我所说,我的模型名称是 tbl_posts,而不是 Post。
猜你喜欢
  • 2012-07-09
  • 1970-01-01
  • 2011-08-26
  • 2013-02-27
  • 2017-10-10
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
  • 2015-04-08
相关资源
最近更新 更多