【问题标题】:How to echo a variable from the function如何从函数中回显变量
【发布时间】:2010-06-23 12:49:48
【问题描述】:

如何从函数中回显一个变量?这是一个示例代码。

功能测试() { $foo = 'foo'; //变量 } 测试(); //执行函数 回声 $foo; // 没有结果打印出来

【问题讨论】:

  • 你只是想打印变量吗?为什么不在函数内部打印呢?你想退货吗?还是您只是想在返回后打印它?
  • 你不能打印一个没有在函数之前声明的变量。

标签: php


【解决方案1】:

您的问题的直接答案是将$foo 导入函数的范围:

function test() {

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

更多关于 PHP here 中的变量范围。

然而,在大多数情况下,这是不好的做法。您通常希望从函数中返回所需的值,并在调用函数时将其分配给$foo

   function test()
    { 
      return "foo"; 
     }

   $foo = test();

   echo $foo;  // outputs "foo"

【讨论】:

    【解决方案2】:

    变量生命范围就在函数内部。您需要将其声明为全局,以便能够在函数外部访问它。

    你可以这样做:

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

    或者按照建议将其声明为全局。为此,请查看此处的手册: http://php.net/manual/en/language.variables.scope.php

    【讨论】:

      【解决方案3】:
      function test() {
        return 'foo';   //the variable
      }
      
      $foo = test();   //executing the function
      
      echo $foo;
      

      【讨论】:

        【解决方案4】:

        您的$foo 变量在函数外部不可见,因为它只存在于函数的范围内。你可以通过多种方式做你想做的事:

        来自函数本身的回显:

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

        回显返回结果:

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

        使变量全局化

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

        【讨论】:

          【解决方案5】:

          我个人会这样做。

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

          在函数参数部分使用与号告诉函数“全球化”输入变量,因此对该变量的任何更改都将直接更改函数范围之外的变量!

          【讨论】:

          • 只要在调用 test() 之前定义了 $foobar 以提高可读性...尽管 PHP 会动态创建 $foobar
          • $foobar 应该由 PHP 创建超出其范围!没有用户应用程序创建它,所以我的示例应该通过在外部范围内创建 $foobar 来正常工作! - php.net/manual/en/language.references.pass.php
          猜你喜欢
          • 1970-01-01
          • 2017-04-18
          • 1970-01-01
          • 2014-04-02
          • 2010-09-07
          • 1970-01-01
          • 2022-01-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多