php内联函数,如.net

时间:2016-05-11 07:55:38

标签: php function inline inline-functions

我想在php中编写一个内联函数,如下所示

例如:

$c = getCountry();
$b = getZones();
$a = [
      'x' => function() use ($c, $b)
             {
                 if ( isset($c[0]) )
                     return getZonesByCountryId($c[0]['id']);
                 else
                     return $b;
             }
     ];

我收到此错误:“类Closure的对象无法转换为字符串” 我在.net中编写内联函数就像我上面做的那样。请帮帮我!!!

1 个答案:

答案 0 :(得分:2)

'x'的值将是一个函数;匿名函数本身将分配给'x',而不是其返回值。要分配其返回值,您需要实际执行以下函数:

$a = ['x' => call_user_func(function() use ($c, $b) {
          if (isset($c[0])) {
              return getZonesByCountryId($c[0]['id']);
          } else {
              return $b;
          }
      })];

然而,在这种特殊情况下,使用如此复杂的解决方案绝对没有意义,当这样做会很好:

$a = ['x' => isset($c[0]) ? getZonesByCountryId($c[0]['id']) : $b];