I am having trouble getting the value of a variable which is in a function outside the function...
Example:
function myfunction() {
$name = 'myname';
echo $name;
}
Then I call it...
if (something) {
myfunction();
}
This is echoing $name
, but if I try to echo $name
inside the input value it won't show:
<input type="text" name="name" value="<?php echo $name ?>"
How can I get access to this variable value?
The $name
variable is local until you explicitly define it as global:
function myfunction() {
global $name;
$name = 'myname';
echo $name;
}
But this doesn't seem like a good use of globals here. Did you mean to return the value and assign it? (Or just use it once?)
function myfunction() {
$name = 'myname';
return $name;
}
...
$name = myfunction();
Read abour variable scope The variable has local scope. You have to made it global. But better, use some template engine or implement Registry
Its a matter of scope..
http://php.net/manual/en/language.variables.scope.php
Just as when you're in a closed room, we cant see what you do, but if you open a door, or put in a video camera people can, or can see limited things, or hear limited things.. this is how stuff works in computers too
You should read the php page about scope.
To do what you want there are two solutions:
$name
global, orreturn
the variable from the functionThe $name
variable is local in that function. So it's accessible only inside that function. If you want it to be accesible everywhere you can do the following:
global $name;
still declare it outside but pass her as a function argument by reference:
function myFunc(&$name) { $name = "text"; }