我在使用全局变量时遇到一些错误。我在全局范围内定义了$ 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。
提前感谢您的帮助。
您错过了调用函数的操作,还删除了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'];
}
此受保护的函数无法访问该变量。因此,通过删除protected。
使用。<?php
$tmp = "testing";
function testFunction(){
global $tmp;
echo ($tmp);
}
受保护的功能必须在这样的类中:
Class SomeClass extends SomeotherClass {
public static $tmp = "testing";
protected function testFunction() {
echo self::$tmp;
}
}
我在这里遇到同样的问题。因为在任何函数中都可以看到$ GLOBALS,所以我使用了这个:
<?php
$GLOBALS['tmp'] = "testing";
function testFunction(){
echo( $GLOBALS['tmp'] );
}