Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie: variables in function

Status
Not open for further replies.

Leijonamieli

Programmer
Nov 28, 2005
6
FI
<?php
$text= "hmm";

function foo() {
var_dump($text);
}

foo();
?>

How do I access $text? This only prints NULL.
 
Is this what you want?
Code:
<?

$GLOBALS[text]= "hmm";

function foo() {
var_dump($GLOBALS[text]);
}

foo();

?>
 
Either that or you have to explicitly pass the variable into the function
Code:
$text= "hmm";

function foo($var) {
var_dump($var);
}

foo($text);


For you see, variables have scope, that is trhey have certain places where they exist, unless you use rockstardub's suggestion and make them global.



----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Hard to say what exactly is the best solution in your case, however, I would probably do something like:
Code:
<?php
$text= "hmm";

function foo() 
{
   [b]global $text;[/b]
   var_dump($text);
}

foo();
?>
Which will pull $text from outside the function. Read more on variable scope in PHP manual:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top