0

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?

1
  • Did you try to globalize your variable. i.e. define it as global: global $name; $name= 'myname';? Commented Oct 17, 2012 at 14:04

5 Answers 5

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

exactly what i was about to write :-) people forget global is two-way
0

Read abour variable scope The variable has local scope. You have to made it global. But better, use some template engine or implement Registry

Comments

0

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

Comments

0

You should read the php page about scope.

To do what you want there are two solutions:

  1. Make $name global, or
  2. return the variable from the function

Comments

0

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:

  • declare it outside the function and inside the function type: global $name;
  • still declare it outside but pass her as a function argument by reference:

    function myFunc(&$name) { $name = "text"; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.