全局变量不在php中工作

时间:2013-09-17 11:13:38

标签: php php-5.4

我在使用全局变量时遇到一些错误。 我在全局范围内定义了一个$ var并尝试在函数中使用它但在那里无法访问它。请参阅以下代码以获得更好的解释:

档案a.php:

<?php

  $tmp = "testing";

  function testFunction(){
     global $tmp;
     echo($tmp);
  }

关于如何调用此函数的一些内容。

文件b.php:

<?php
  include 'a.php'
  class testClass{
    public function testFunctionCall(){
        testFunction();
    }
  }

使用以下方法调用上述'b.php':

$method = new ReflectionMethod($this, $method);
$method->invoke();

现在所需的输出是'测试'但接收的输出是NULL。

提前感谢您的帮助。

4 个答案:

答案 0 :(得分:4)

您错过了调用您的功能并删除了 protected 关键字。

试试这种方式

<?php

  $tmp = "testing";

  testFunction(); // you missed this

  function testFunction(){  //removed protected
     global $tmp;
     echo($tmp);
  }

相同的代码,但使用 $GLOBALS ,可以获得相同的输出。

<?php

$tmp = "testing";

testFunction(); // you missed this

function testFunction(){  //removed protected
    echo $GLOBALS['tmp'];
}

答案 1 :(得分:1)

此受保护的函数无法访问该变量。因此,请删除受保护的

<?php

  $tmp = "testing";

   function testFunction(){
     global $tmp;
     echo ($tmp);
  }

答案 2 :(得分:0)

受保护的函数需要在这样的类中:

 Class SomeClass extends SomeotherClass {

   public static $tmp = "testing";

   protected function testFunction() {

      echo self::$tmp;

   }
}

答案 3 :(得分:0)

我在这里遇到同样的问题。 因为在任何函数中都可以看到$ GLOBALS,所以我使用了它:

<?php

  $GLOBALS['tmp'] = "testing";

  function testFunction(){

     echo( $GLOBALS['tmp'] );
  }
相关问题