开发者

How to retrieve variables defined in a particular include file in php?

开发者 https://www.devze.com 2023-02-09 10:56 出处:网络
I want to know all the variables that have been declared within an include file. Example code is: Include file:开发者_如何学C

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

Example code is:

  1. Include file:

    开发者_如何学C
    <?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?


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 (!)

0

精彩评论

暂无评论...
验证码 换一张
取 消