全局变量在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();

现在所需的输出是'testing',但收到的输出为NULL。

提前感谢您的帮助。

php php-5.4
4个回答
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
投票

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

使用。
<?php

  $tmp = "testing";

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

0
投票

受保护的功能必须在这样的类中:

 Class SomeClass extends SomeotherClass {

   public static $tmp = "testing";

   protected function testFunction() {

      echo self::$tmp;

   }
}

0
投票

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

<?php

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

  function testFunction(){

     echo( $GLOBALS['tmp'] );
  }
© www.soinside.com 2019 - 2024. All rights reserved.