Hi guys
How can I create a variable in a function then access it outside of the function
function checkDomain(){
$variable='hello';
}
echo"$variable";
What is the correct way to do this?
Hi guys
How can I create a variable in a function then access it outside of the function
function checkDomain(){
$variable='hello';
}
echo"$variable";
What is the correct way to do this?
function namething () { return 'hello'; }
echo namething();
Without returning the variable from the function, there is no way to do this. Variables (and constants, and everything else) filter down, but never percolate up. So for instance, if you did:
$var = "foo";
function echoVar(){
echo $var;
}
echoVar();
You would see an echo of “foo” as expected. This is because things declared outside a function are visible within the function, but things declared inside a function are not visible outside the function. Generally, you don’t want to do things like this, however, because they tend to lead to unmaintainable code. If you need a variable in a function/method, you should usually pass it to the method via the method call.
No you wouldn’t.
This is because things declared outside a function are visible within the function,
No they aren’t.
Read more about it here: http://www.php.net/manual/en/language.variables.scope.php