0

I want to know all the variables that have been declared within an include file.

Example code is:

  1. Include file:

    <?php
    $a = 1;
    $b = 2;
    $c = 3;
    $myArr = array(5,6,7);
    ?>
    
  2. Main file:

    <?php
    
    $first = get_defined_vars();
    include_once("include_vars.php");
    $second = get_defined_vars();
    
    $diff = array_diff($second ,$first);
    var_dump($diff);
    
    $x = 12;
    $y = 13;
    ?>
    

My attempt to use difference of get_defined_vars() does not seem to give accurate information. It gives:

array(2) {
  ["b"]=>
  int(2)
  ["c"]=>
  int(3)
}

$a and $myArr seem to be missing. What are other methods I can use?

1
  • 3
    Don't use global variables. Let me repeat that. Don't use global variables. Pass around variables wrapped in containers such as an object. Note that I said pass around, not call globally. Read about Dependency Injection... Commented Feb 8, 2011 at 14:06

1 Answer 1

2

It's really not a good thing to do this, hope it's needed just for debugging. Then you should find a difference between keys of the arrays that get_defined_vars return, not between their values:

$diff = array_diff(array_keys($second),array_keys($first));

If you don't want to include your file, a more complicated way would be using Tokenizer:

$tokens = token_get_all(file_get_contents("include_vars.php")); 

foreach($tokens as $token) {
    if ($token[0] == T_VARIABLE)
        echo $token[1] . ', ';
}

That would return all variables, even non-globals ones and the ones that were unset in that script (!)

Sign up to request clarification or add additional context in comments.

3 Comments

Yes it is needed just for debugging purpose. Not a part of core implementation.
I would also appreciate if you can suggest other methods too.
Finding difference between those arrays is the best method. Added about Tokenizer, but I wouldn't use it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.