php - PHP回调函数中的动态变量
问题描述
我有一个私有函数来返回一个选项数组,这些选项表示一个回调和其他选项,如模板、表单等。这里的代码:
/**
* @return array
*/
private function options()
{
$options = [
'general' => [
'form' => GeneralConfigType::class,
'template' => 'general.html.twig',
'title' => 'Configuración General',
'ignoreFields' => ['slider', 'social'],
'uploadedFields' => [],
'callbacks' => ['generalData']
],
'business' => [
'form' => ConfigurationType::class,
'template' => 'business.html.twig',
'title' => 'Configuración de Empresa',
'ignoreFields' => [],
'uploadedFields' => ['image','favicon','login_icon','sidebar_icon'],
'callbacks' => ['businessImage']
],
];
return $options;
}
现在这是我的疑问,除了指出您必须在 key 中执行的功能之外callback
,我可以传递variables
我将需要的功能callback
吗?我尝试了几种方法,但都没有奏效。
例子:
前:
'callbacks' => ['generalData']
后:
在此示例中,我分配了“$”,但如果是唯一的字符串,我可以这样做,我只是在寻找一种将它需要的变量传递给回调的方法,仅此而已。
'callbacks' => ['generalData' => '$configurationData, $configuration, $form, $request']
这段代码将是在其他方法中执行所有内容的地方:
if (!empty($options[ 'callbacks' ])) {
foreach ($options[ 'callbacks' ] as $callback => $variables) {
$this->$callback($variables);
}
}
解决方案
如果我理解正确,您希望将变量的名称存储在选项数组中,然后在回调函数中使用该变量。
当我完成这种类型的事情后,我发现将变量名称存储为文本并$
从存储在数组中的名称中省略掉更容易。然后我在检索它时使用一个变量变量。
无论哪种方式,我认为您在执行方面需要更多代码。又一个循环:
if (!empty($options[ 'callbacks' ])) {
foreach ($options[ 'callbacks' ] as $callback => $variables) {
foreach($variables as $variable){ // extra loop to get the variables
$this->$callback[$$variable];
// This is where it gets tricky, and depends on how you wish to format.
// The variables are currently part of an array, thus the array notation
// above. By using the stored name only, and a variable variable, you
// should be able to get to the var you need
}
}
}
推荐阅读
- kubernetes - Helm 只更新一个属性
- html - 使幻灯片适合网格
- python - 多索引数据框中多列标准的行选择(更有效的解决方案?)
- javascript - 使用 JS 函数以 onsubmit 形式返回值
- jquery - 为ajax URL启用spring安全性时重定向到Ajax Post Request上的登录页面
- java - 将两个 pojo 和输出差异与另一个 pojo 进行比较
- java - 构造函数 StringEntity(String, String, String) 已弃用
- ios - UITableView 在用户释放它之前重置为起始位置
- python - Python 错误:UnboundLocalError:赋值前引用了局部变量“score1”
- r - 如何将矩阵添加到 data.frame?