Satch3000
Satch3000

Reputation: 49384

Variable from function not displaying outside the function

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

Answers (5)

lucassp
lucassp

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:

  • 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"; }

Upvotes: 0

Dennis Haarbrink
Dennis Haarbrink

Reputation: 3760

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

Upvotes: 0

BugFinder
BugFinder

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

Maxim Krizhanovsky
Maxim Krizhanovsky

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

Ry-
Ry-

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

Related Questions