如何在 admin class 中将函数作为参数传递

How to pass a function as a parameter in admin class

早上好,我在使用 sonata admin bundle 时遇到一点问题,假设我有一个 returns 字符串的函数,我想将此函数的结果作为参数传递到数据网格中:类似:

protected $datagridValues = array (
'email' => array ('type1' => 2, 'value' => function()), // type 2 : >
'_page' => 1, // Display the first page (default = 1)
'_sort_by' => 'id' 
);

有谁知道这样做的方法吗?谢谢

问题是

中的 function()
'email' => array ('type1' => 2, 'value' => function())

传递一个正确的变量,它将起作用。

'email' => array ('type1' => 2, 'value' => 'myValue')

编辑

要在参数中传递函数(命名为 回调函数),您必须在参数中传递回调名称,并使用 call_user_func 到 运行 然后:

function mycallback(){
    // do things
}

protected $datagridValues = array (
    'email' => array ('type1' => 2, 'value' => 'mycallback')
    '_page' => 1,
    '_sort_by' => 'id' 
);

然后你可以在你的脚本中做:

call_user_func($datagridValues['email']['value']);

在数组中你不能调用函数.. 你可以这样做。

$var = function_name();

protected $datagridValues = array (
'email' => array ('type1' => 2, 'value' => $var), // type 2 : >
'_page' => 1, // Display the first page (default = 1)
'_sort_by' => 'id' 
);

您可以覆盖 getFilterParameters() 方法来更改您的 $datagridValues:

public function getFilterParameters()
{
    $this->datagridValues = array_merge(array(
            'email' => array ('type1' => 2, 'value' => function()),
        ), $this->datagridValues);

    return parent::getFilterParameters();
}