简体   繁体   English

PHP,闭包和提取参数

[英]PHP, closures and extracting parameters

I'm not sure how to best title this so I thought I would post an example of what I'm trying to achieve. 我不确定如何最好地标题,所以我想我会发布一个我想要实现的例子。 I've super-simplified this for now. 我现在已经超级简化了这一点。

So first is the very basic class that will do the action. 首先是将要采取行动的最基本的类。

abstract class AuditedSave extends AuditedSaveImplementation
{

    public static function run($callback = null)
    {
        return new AuditedSaveImplementation($callback);
    }

}

class AuditedSaveImplementation
{

    public function __construct(Closure $closure)
    {
        echo ' - I ran before'; // point 1, $test = 0
        $closure();
        echo ' - i ran after!'; // point 2, $test = 1
    }

}

Then the code that calls it. 然后是调用它的代码。

$test = 0;

AuditedSave::run(function() use ($test)
{
    $test = 1;
});

So between point 1 and 2 as commented, the closure runs and would set the value of $test to 1. However, I want to store the value of whatever is passed as the first parameter (in this case, $test ) as a copy of what it was at the time of function calling - which will always run, the closure then modifies it (this is the part that can be variable), and then afterwards a comparison gets made and actions happen based on differences - which will always run. 因此,在注释的第1点和第2点之间,闭包运行并将$ test的值设置为1.但是,我想将作为第一个参数(在本例中$test )传递的任何值的值存储为副本在函数调用的时候 - 它将始终运行,闭包然后修改它(这是可变的部分),然后进行比较并根据差异进行操作 - 这将始终运行。

However, in order to do this, I need to be able to access the $test variable within the __construct() method of AuditedSaveImplementation without knowing what it's called. 但是,为了做到这一点,我需要能够在AuditedSaveImplementation__construct()方法中访问$ test变量,而不知道它的名称。

Is this possible at all? 这有可能吗?

You can use ReflectionFunction class getStaticVariables method to get params passed to closure via use . 您可以使用ReflectionFunctiongetStaticVariables方法来获取通过use传递给闭包的params。 Like this: 像这样:

class AuditedSaveImplementation
{

    public function __construct(Closure $closure)
    {
        echo ' - I ran before'; // point 1, $test = 0
        $closureReflection = new ReflectionFunction($closure);
        $variables = $closureReflection->getStaticVariables();
        var_dump($variables);
        $closure();
        echo ' - i ran after!'; // point 2, $test = 1
    }

}

But as mentioned in the comments you should rethink how you do this. 但正如评论中所提到的,你应该重新思考如何做到这一点。 It's not a good approach. 这不是一个好方法。 Try to create a special class as was suggested in comments. 尝试按照评论中的建议创建一个特殊类。

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

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