简体   繁体   English

使用动态变量作为模型名称

[英]Using a dynamic variable as the name of a model

How would I go about calling a model using a dynamic variable? 如何使用动态变量调用模型? I thought $nameOfModel::all() would work. 我认为$nameOfModel::all()可以工作。 I have 4 different tables that need to make use of the same function. 我有4个需要使用相同功能的不同表。

This is what a normal call looks like tableOne::all() so I'm trying to have something like: 这是正常的调用,看起来像tableOne::all()所以我正在尝试类似:

$table = 'tableOne';
$table = 'tableTwo';
$table = 'tableThree';
$table = 'tableFour';

$contents = $table::all();

If you want to use model name as a dynamic variable, you can easily achiev this with ${} call. 如果要将模型名称用作动态变量,则可以通过${}调用轻松实现。

For variable, which you mentioned it will be: 对于变量,您提到的将是:

${$nameOfModel}::all()

You can also find more details about variable names (variables, functions, ...) in PHP doc: 您还可以在PHP doc中找到有关变量名称(变量,函数等)的更多详细信息:

Variables variable 变量变量

Variable functions 可变功能

Based on comments I think, that you need define your class as first, so your code must look like: 基于我的评论,您需要首先定义您的类,因此您的代码必须如下所示:

$table = 'tableOne';
$table = 'tableTwo';
$table = 'tableThree';
$table = 'tableFour';

$class = new $table;
$contents = $class::all();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM