Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: query all variables defined inside function scope

Tags:

php

This is just out of curiosity, but I was wondering if there was a way to query all the variables defined inside the scope of a function (exclusively within this scope, and from within that function) and put them in an associative array. Something like an extended get_defined_vars function.

The reason is that it would be nice to be able to save the 'state' of an execution at any point in the program, for instance to debug, log, handle exceptions, or even pass the entire scope of a function to another one. If I'm not mistaken, I think get_object_vars allows doing this with objects.

like image 484
Jonathan H Avatar asked Jul 11 '26 20:07

Jonathan H


1 Answers

From the comments of PHP.net

// The very top of your php script
$vars = get_defined_vars();

// Now do your stuff
$foo = 'foo';
$bar = 'bar';

// Get all the variables defined in current scope
$vars = array_diff(get_defined_vars(),$vars);

echo '<pre>';
print_r($vars);
echo '</pre>';
like image 143
Carlos Goce Avatar answered Jul 13 '26 12:07

Carlos Goce