首页 > 解决方案 > 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);         
       }           
    }

标签: php

解决方案


如果我理解正确,您希望将变量的名称存储在选项数组中,然后在回调函数中使用该变量。

当我完成这种类型的事情后,我发现将变量名称存储为文本并$从存储在数组中的名称中省略掉更容易。然后我在检索它时使用一个变量变量。

无论哪种方式,我认为您在执行方面需要更多代码。又一个循环:

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
      }         
   }           
}

推荐阅读