tags:

views:

76

answers:

5

How to echo a variable from the function? This is an example code.

function test() {
  $foo = 'foo';   //the variable
}

test();   //executing the function

echo $foo;   // no results in printing it out

+2  A: 

The variable life scope is just inside the function. You need to declare it global to be able to access it outside the function.

You can do:

function test() {
  $foo = 'foo';   //the variable
  echo $foo;
}

test();   //executing the function

Or declare it global as suggested. To do it so, have a look at the manual here: http://php.net/manual/en/language.variables.scope.php

pakore
jajaja what are you doing replying PHP, you will get sick :p
Gabriel Sosa
+6  A: 

The immediate answer to your question would be to import $foo into the function's scope:

function test() {

  global $foo;
  $foo = 'foo';   //the variable
}

More on variable scope in PHP here.

this is, however, bad practice in most cases. You will usually want to return the desired value from the function, and assign it to $foo when calling the function.

   function test()
    { 
      return "foo"; 
     }

   $foo = test();

   echo $foo;  // outputs "foo"
Pekka
+1  A: 
function test() {
  return 'foo';   //the variable
}

$foo = test();   //executing the function

echo $foo;
Mark Baker
A: 

Your $foo variable is not visible outside of the function, because it exists only in the function's scope. You can do what you want several ways:

Echo from a function itself:

function test() {
    $foo = 'foo';
    echo $foo;
}

Echo a return result:

function test() {
    $foo = 'foo';   //the variable
    return $foo;
}

echo test();   //executing the function

Make the variable global

$foo = '';

function test() {
    Global $foo;
    $foo = 'foo';   //the variable
}

test();   //executing the function

echo $foo;
Igor Zinov'yev
A: 

Personally I would do.

function test(&$foo)
{
    $foo = 'bar';
}

test($foobar);

echo $foobar;

Using the ampersand within the function parameters section tells the function to "globalization" the input variables so any changes to that variable will directly change the one outside the function scope!

RobertPitt
As long as $foobar is defined before calling test() for readability... despite the fact that PHP will create $foobar on the fly
Mark Baker
$foobar should be created by PHP Outside its scope! without the user application creating it, so my example should work fine by creating $foobar within the outer scope! - http://www.php.net/manual/en/language.references.pass.php
RobertPitt