Thursday, July 30, 2009

How do I declare a variable in PHP so I can use it inside a function?

In PHP, I need to declare a variable and be able to use it inside a function. Is there any way I can do this? I tried "Global $myvar=0;" but i get the following error:





Parse error: syntax error, unexpected '=', expecting ',' or ';' in C:\Program Files\EasyPHP 2.0b1\www\test.php on line 2





and if I take out the "=" ("Global $myvar=0; $new=0; echo $new;") I get this:


Parse error: syntax error, unexpected T_ECHO in C:\Program Files\EasyPHP 2.0b1\www\test.php on line 4

How do I declare a variable in PHP so I can use it inside a function?
the global call needs to be inside the function, but the variable initialization can be outside... for example:





$myvar = 0;





function test() {


global $myvar;





echo $myvar;


}





EDIT: even though you are able to initialize the variable outside of the function, you MUST use the word global inside of the function like i've shown above... just wanted to clarify. hope this helps :-)





the problem with this:


%26gt;%26gt;%26gt;%26gt;%26gt;("Global $myvar=0; $new=0; echo $new;")%26lt;%26lt;%26lt;%26lt;%26lt;





is that all of this is inside the ""... take them out
Reply:or





%26lt;?php





$myvariable = "Hello";





function myFunction($variable)


{


$string = $variable." World.";


return $string;


}





echo myFunction($myvariable);


?%26gt;


No comments:

Post a Comment