gpt4 book ai didi

php - 在 PHP 中序列化或散列闭包

转载 作者:可可西里 更新时间:2023-11-01 12:42:53 27 4
gpt4 key购买 nike

这必然会引发设计问题,但我想在 PHP 中对闭包进行序列化或散列处理,以便我拥有该闭包的唯一标识符。

我不需要能够从中调用闭包,我只需要一个可以从闭包本身的内部和外部访问的唯一标识符,即接受 closer 的方法需要生成一个该闭包的 id,并且闭包本身需要能够生成相同的 id

到目前为止我尝试过的事情:

$someClass = new SomeClass();

$closure1 = $someClass->closure();

print $closure1();
// Outputs: I am a closure: {closure}

print $someClass->closure();
// Outputs: Catchable fatal error: Object of class Closure could not be converted to string

print serialize($closure1);
// Outputs: Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'Closure' is not allowed'

class SomeClass
{
function closure()
{
return function () { return 'I am a closure: ' . __FUNCTION__; };
}
}

Reflection API 似乎也没有提供任何我可以用来创建 ID 的东西。

最佳答案

我的解决方案更通用,并尊重闭包的静态参数。为了达到目的,您可以在闭包内传递对闭包的引用:

class ClosureHash
{
/**
* List of hashes
*
* @var SplObjectStorage
*/
protected static $hashes = null;

/**
* Returns a hash for closure
*
* @param callable $closure
*
* @return string
*/
public static function from(Closure $closure)
{
if (!self::$hashes) {
self::$hashes = new SplObjectStorage();
}

if (!isset(self::$hashes[$closure])) {
$ref = new ReflectionFunction($closure);
$file = new SplFileObject($ref->getFileName());
$file->seek($ref->getStartLine()-1);
$content = '';
while ($file->key() < $ref->getEndLine()) {
$content .= $file->current();
$file->next();
}
self::$hashes[$closure] = md5(json_encode(array(
$content,
$ref->getStaticVariables()
)));
}
return self::$hashes[$closure];
}
}

class Test {

public function hello($greeting)
{
$closure = function ($message) use ($greeting, &$closure) {
echo "Inside: ", ClosureHash::from($closure), PHP_EOL, "<br>" ;
};
return $closure;
}
}

$obj = new Test();

$closure = $obj->hello('Hello');
$closure('PHP');
echo "Outside: ", ClosureHash::from($closure), PHP_EOL, "<br>";

$another = $obj->hello('Bonjour');
$another('PHP');
echo "Outside: ", ClosureHash::from($another), PHP_EOL, "<br>";

关于php - 在 PHP 中序列化或散列闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13983714/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com