【问题标题】:Can I use a variable as the name of a class?我可以使用变量作为类的名称吗?
【发布时间】:2017-02-27 05:36:51
【问题描述】:

这也有效:

$news_single = news::whereid($post_id)->first();

但这会引发错误:

$class_name  = 'news';
$news_single = $class_name::whereid($post_id)->first();

错误:

PostController.php 第 20 行中的 FatalErrorException: 找不到类“新闻”

我该如何解决?


我使用变量作为类名的意图是进行动态查询(有点)。我的意思是我得到 URL 的类名并通过它指定正确的 Model。像这样的:

public function ShowPost(Request $request){
    $post_id    = $request->segment(2);
    $class_name = $request->segment(1);
    $post       = $class_name::whereid($post_id)->first();
    return view('ShowPost',compact('post'));
}

【问题讨论】:

  • {yes} 但我认为这是个坏主意
  • @nogad 为什么是个坏主意?
  • @stack 任何命名空间到类??
  • @ThunderBird 是的,我已经像use App\news; 一样附加了那个类。正如我在问题中提到的,这有效news::whereid($post_id)->first();。但这不起作用:$class_name::whereid($post_id)->first();

标签: php laravel oop


【解决方案1】:

我假设某个命名空间中的 news 类。

你必须在字符串前面加上命名空间。

$class_name  =  'App\\' .'news';
$news_single = $class_name::whereid($post_id)->first();

【讨论】:

    猜你喜欢
    • 2011-10-14
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多