Forum Moderators: coopster
I have a document that starts by including a variables.php-file and then a functions.php file. Is there a way to get the variables in the variables.php-file to work inside the functions in the functions.php-file without sending them when I access the function?
Supposedly the use of global would do this, but any way I have tried this it doesn't work.
Also, does anyone know of a good newbie tutorial for PHP-functions?
Variable scope in PHP
A variable declared outside any function is a global variable. It exists everywhere in the script. References to variables outside any function refer to global variables.
A variable declared inside a function is a local variable for that function. It only exists inside that function. References to variables inside any function refer to that function's local variables.
Some language variable names are superglobal. A reference to a variable that could refer to a superglobal always resolves to the superglobal.
There is a superglobal array called $GLOBALS[], which holds all global variables existing in the script, indexed by name.
Example
<?php
$a = "this is the global variable \$a";
function example(){
$a = "this is example's local variable \$a";
echo $a . "\n" . $GLOBALS['a'];
}
example();
?>
I guess this completely answers the original question and some more which are related.
Now, I'd like to give my opinion about the diference between phpfreaks and php.net resources:
The phpfreaks link given by dreamcatcher is a tutorial.
php.net strong point, the manual pages, are not a tutorial, but a reference.
A tutorial explains something following a 'didactic' order: if you need to understand variables to be able to understand functions, then a tutorial will explain variables first and functions later. It tries to explain something from the beginning (or from a stablished start point, in the case of most advanced tutorials) up to some point. It could be compared to a line going upwards.
In the other hand, a reference doesn't try to explain a whole, but all of its parts independently. It could be compared to a grid.
A tutorial is useful if you want to learn something, like a language. A reference is your tool when you already know the whole and have a doubt of a precise point, like the syntax for a given function.
Intelligence implies knowing which tool to use to resolve each problem.
Hoping be useful,
Herenvardö