简体   繁体   English

php类方法的无名函数返回值

[英]php class method return value of nameless function

Hello I have the following method. 您好,我有以下方法。 I would like to use a nameless function and change some data before the method returns, instead of creating a separate function to localize the results from the database query. 我想使用一个无名函数并在方法返回之前更改一些数据,而不是创建一个单独的函数来本地化数据库查询的结果。 I would also like the method to return the filtered data from the nameless function. 我还希望该方法从无名函数返回过滤的数据。 What am I doing wrong in the following code? 我在以下代码中做错了什么?

public function getStats($request){

    // some custom input filtering

    $params = array('uid' => $this->uid);
    $reply = $db->get($query,$params);

    return function() use (&$reply){

        //localization of some strings

        return $reply;
    };
} 

Instead of returning the value returned by your anonymous function, you're returning the function itself. 而不是返回匿名函数返回的值,而是返回函数本身。 Try this instead: 尝试以下方法:

public function getStats($request){

    // some custom input filtering

    $params = array('uid' => $this->uid);
    $reply = $db->get($query,$params);

    $myfunction = function() use ($reply){

        //localization of some strings

        return $reply;
    };

    return $myfunction();
} 

Also, no need to pass $reply by reference. 另外,无需通过引用传递$reply

In PHP nameless functions are known as anonymous functions or closures. 在PHP中,无名函数称为匿名函数或闭包。 Here is an example: 这是一个例子:

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

For more information see docs . 有关更多信息, 请参阅docs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM