-1

If I do print_r in $GLOBALS I have all globals vars.

But I need something like this:

function foo() {
   $a = 1;
   $b = 2;
   for($i = 0; $i < 10; $i++);
}

print_r(find_variables_in_function('foo')); // results: array(a => 1, b => 2, i => 10);

I'm trying implement a new feature in code.google.com/p/webgrind/ - since this tool give me functions in run time, I can generate a chart by variables size at end of all functions called.

$x = 2;
$y = 3;

function foo() {
    $a = 1;
    $b = 2;
    for ($i = 0; $i < 10; $i++)
        ;

    print_r(get_defined_vars()); // has no side effects - print null string
}
Ragen Dazs
  • 2,115
  • 3
  • 28
  • 56

2 Answers2

3

get_defined_vars() returns an array of all the variables defined in the scope in which it was called. If you call that from within the function you will get the variables defined in that function here's the documentation:

http://php.net/manual/en/function.get-defined-vars.php

eg:

<?php 
   function foo() {
       $a = 'first';
       $b = 'second';
       $c = get_defined_vars();
       print "vars=";print_r($c);print"\n";        
   }
   foo();
?>   

Here what it prints

$ php testgdvars.php
vars=Array
(
    [a] => first
    [b] => second
)
Peter Wooster
  • 6,009
  • 2
  • 27
  • 39
0

Outside of the function, the variables aren't defined. Except static variables, and those are private to the function.

Why not just add a var_dump($a,$b,$i); to the end of the function?

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592