Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string representation of anonymous function

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 string
  • var_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.

like image 515
Michael Osl Avatar asked Mar 10 '14 18:03

Michael Osl


1 Answers

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

like image 180
PeeHaa Avatar answered Oct 07 '22 18:10

PeeHaa