View Full Version : list all variables in an included file
22-06-2011, 01:52 PM
get_defined_vars() gives you everything, which is not what I need. I'm looking for a function/codes to give me a list of variables that are defined in a particular included file. Is there such a built-in function in PHP?
22-06-2011, 03:21 PM
I would think not. And that would be by design.
An include() is meant to run the code as if the code is within the file including it and as such, there should be no distinction between the variables within an include and its includer.
If you need variables to belong to a collection, put them into an array.
Alternatively put them into a class and use get_object_vars()
22-06-2011, 03:25 PM
Variable Scope http://au.php.net/manual/en/language.variables.scope.php
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.
22-06-2011, 05:59 PM
Thanks Bas. I'm looking for a lazy way of seeing what's in a file and print it to screen for quick referencing...
23-06-2011, 09:35 AM
Could you call get_defined_vars() before and after the file is included and display the difference?
23-06-2011, 02:18 PM
great bloody idea botman! thanks!
23-06-2011, 05:50 PM
for those playing at home:
$a2 = get_defined_vars();
print_r ( array_diff( $a2, $a1 ) );
23-06-2011, 07:46 PM
The concept should work for your usage, however you should use array_diff_assoc()
If $var1 is defined before the include as 'yes'
And $var2 is defined inside the include as 'yes'...
When array_diff() is used, the 2 cancel each other out as they have the same value, and neither is included in the result.
array_diff_assoc() compares the keys of the array, not the values.
ie, in this example it compares the variable names, which is what i think you are after.
24-06-2011, 02:28 PM
that's correct, this only shows those that are unique in the second set.
27-06-2011, 02:39 PM
Franki - from your response, I'm not sure whether you understood what I was saying...
I was saying that you should be using array_diff_assoc() instead of array_diff(). If you knew that, then all good :)
27-06-2011, 06:06 PM
Fantastic, happy to help. :)
What Basil says is a good point/bugfix too.
vBulletin® v3.8.4, Copyright ©2000-2013, Jelsoft Enterprises Ltd.