gpt4 book ai didi

反序列化后的 PHP Doc 注释

转载 作者:可可西里 更新时间:2023-11-01 01:13:36 25 4
gpt4 key购买 nike

来自 PHP (http://php.net/manual/en/class.reflectionmethod.php) 的 ReflectionMethod 实例具有返回方法注释的 getDocComment 方法。这工作正常,除非您使用未序列化的对象。

$ref = new ReflectionClass('a');
var_dump(method_exists($ref, 'getDocComment')); //bool(true)
var_dump($ref->getDocComment()); //bool(false)

$ref = unserialize(serialize($ref));
var_dump(method_exists($ref, 'getDocComment')); //bool(true)
var_dump($ref->getDocComment()); //PHP Warning: Uncaught Error: Internal error: Failed to retrieve the reflection object

是否有任何方法可以测试 ReflectionMethod 对象是否正确定义了文档注释?我的意思是,我不关心在序列化/反序列化之后获取注释,但我想检查调用 getDocComment 是否安全。


编辑:根据建议错误处理+回退的回复,我改写了问题。

我有一些简单的反射缓存(ReflectionMethod 对象数组)。在我使用该缓存中的项目之前,我想检查它的正确性。我不想处理错误,我想“预测错误”。很棒的是像 hasDocComment 方法,它不会产生任何错误,但在任何 ReflectionMethod 对象状态中只返回 true/false。

最佳答案

序列化反射对象的一般方法是错误的。存在针对它的 PHP 错误报告,但它已被设置为“不相关”:

https://bugs.php.net/bug.php?id=70719

原因是,您不能将反射对象再次连接回它的类,因为您必须处理源代码更改和各种事情。相反,您应该做的是,在反序列化时序列化类的名称并从该类生成一个新的反射对象。

代码示例:

class A { }
$ref = new ReflectionClass('A');
var_dump(method_exists($ref, 'getDocComment'));

// serialize only the class name
$refClass = unserialize(serialize($ref->getName()));

// get a new reflection object from that class ...
$ref = new ReflectionClass($refClass);
var_dump(method_exists($ref, 'getDocComment'));

// If you want to serialize an object
$a = new A();
$a2 = unserialize(serialize($a));
$ref = new ReflectionClass(get_class($a2));
var_dump(method_exists($ref, 'getDocComment'));

关于反序列化后的 PHP Doc 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46155528/

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