开发者

How to echo a variable from the function

开发者 https://www.devze.com 2023-01-04 16:50 出处:网络
How to echo a variable from the function? This is an example code. function test() { $开发者_JAVA百科foo = \'foo\';//the variable

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

function test() {
  $开发者_JAVA百科foo = 'foo';   //the variable
}

test();   //executing the function

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


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"


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


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

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

echo $foo;


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;


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消