Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/forums/php/)
-   -   using variables declared outside of a function (http://www.go4expert.com/forums/using-variables-declared-outside-t24316/)

pein87 30Dec2010 02:56

using variables declared outside of a function
 
Well I'm sure someone here has wondered why wont my function use the variable I defined outside of it like it does in javascript? Php does not have global variables by default so if you define a variable in a function it is closed for use in that function naturally but if you define a variable you can use it in a function by setting it as global.

PHP Code:

<?php

$myName 
"pein87";

function 
sayMyName()
{

    echo 
$myName;

}

sayMyName();

?>

The above will give an error call to undefined variable myName.

To get around this we can use global declaration in the function.

GLOBAL
This makes the variable global so it will use the value from a variable not defined in the function. This makes the variables scope global.

PHP Code:

<?php

$myName 
"pein87";

function 
sayMyName()
{

   global 
$myName;

    echo 
$myName;

}

sayMyName();

?>

The above would print "pein87" on the screen because its now using the global variable $myName.


All times are GMT +5.5. The time now is 12:11.