Reputation: 49384
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?
Upvotes: 0
Views: 93
Reputation: 4167
The $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";
}
Upvotes: 0
Reputation: 3760
You should read the php page about scope.
To do what you want there are two solutions:
$name
global, orreturn
the variable from the functionUpvotes: 0
Reputation: 17858
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
Upvotes: 0
Reputation: 26699
Read abour variable scope The variable has local scope. You have to made it global. But better, use some template engine or implement Registry
Upvotes: 0
Reputation: 224913
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();
Upvotes: 2