#####问题产生原因:
有时我们需要将某个字符串转为变量名,下面我们来看下如何实现吧。比如要将'work'变成$work,希望可以帮助到有需要的朋友。
```
$str = 'work';
```
想产生一个$work变量,使用大括号即可。
```
${$str}
```
#####使用场景:
在做统计的时候需要将多张表实例化,本文是基于Thinkphp5.0(这不影响),我在构造函数中示例化了需要用到的表,在统计是根据模块去统计数据所以,需要循环模块然后去统计数据(模块名称和表名称一一对应)
这时候如果直接使用`$this->$v['name']`会保存因为`$v['name']`是字符串。这里使用大括号将`$v['name']`包裹起来就可以了,可能我的需求比较奇怪吧。最后附上渣渣代码:
```
namespace app\service\controller;
use think\Db;
class Count extends Base{
private $accident;
public function construct(Request $request = null)
{
parent::construct($request);
//
if (!isset($this->accident)){
$this->accident = Db::name('accident');
}
}
public function index()
{
//总数
$result['total'] = $this->_counts($modules, $module, $where);
return json(['status' => 1, 'result' => $result]);
}
//总数统计
public function _counts($modules, $module, $where, $date = null)
{
$data = 0;
foreach ($modules as $v){
foreach ($module as $m){
if ($v['id'] == $m){
$data += $this->{$v['name']}->whereTime('add_time', $date)->where($where)->count();
}
}
}
return $data;
}
}
```