Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Doc comment after unserialization

Tags:

php

reflection

The ReflectionMethod instance from PHP (http://php.net/manual/en/class.reflectionmethod.php) has the getDocComment method that returns the annotation of a method. This works ok, unless you use unserialized object.

$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

Is there any way of testing if the ReflectionMethod object has correctly defined doc comment? I mean, I do not care about getting the annotation after serialize/unserialize, but I want to check if calling getDocComment is safe.


Edit: According to responses that advice error handling + fallback, I rephrase the Q.

I have some simple cache of reflections (array of ReflectionMethod objects). Until I use item from that cache, I wold like to chech its correctness. I do NOT want to handle error, I want to "predict error". Awesome would be something like hasDocComment method that does not generate any error, but returns only true/false within any ReflectionMethod object state.

like image 656
Jarda Avatar asked Feb 10 '26 14:02

Jarda


1 Answers

The general approach of serializing reflection objects is wrong. There exists a PHP Bug report for it, but it has been set to "irrelevant":

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

The reason is, that you cannot connect a reflection object back to its class again, because you would have to deal with source code changes and all kinds of stuff. What you should do instead is, to serialize the name of the class and generate a NEW reflection object from that class, when you unserialize.

Code Example:

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'));
like image 102
Mathias Mamsch Avatar answered Feb 13 '26 04:02

Mathias Mamsch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!