Let's say I have an anonymous PHP function like this:
<?php
$l = function() { echo "hello world"; };
Is it possible to get a string representation of the anonymous function $l
, i.e. a string containing the function body?
I tried a few things:
echo $l;
PHP Catchable fatal error: Object of class Closure could not be converted to stringvar_dump($l);
class Closure#1 (0) { }echo $l->__toString();
: Call to undefined method Closure::__toString()get_class_methods($l)
returns array('bind', 'bindTo')
, so it seems like no undocumented methods exist$r = new ReflectionClass($l);
: getProperties(), getConstants() and getStaticProperties() are all empty, also $r->__toString()
does not return anything useful.I don't really need this in my code, I just thought it might be useful for logging purposes if something goes wrong. After I couldn't come up with a solution by myself I am curious if it is possible at all.
Your only "real" option is to use an actual PHP parser to parse the anonymous function.
Don't fall in the same trap as @argon did thinking a simple substr_count
based script can actually parse PHP code. It's just too brittle and will break even for the most simple examples in glorious ways.
Point in case:
$dog2 = ['bark'=>function($foo = '{'){}];
Fatal error: Uncaught Exception: Too complex context definition in
https://3v4l.org/CEmqV
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With