我使用全局变量时遇到一些错误.我在全局范围内定义了一个$ var并尝试在函数中使用它但在那里无法访问它.请参阅以下代码以获得更好的解释:
文件a.php:
<?php
$tmp = "testing";
function testFunction(){
global $tmp;
echo($tmp);
}
Run Code Online (Sandbox Code Playgroud)
那么关于如何调用这个函数.
文件b.php:
<?php
include 'a.php'
class testClass{
public function testFunctionCall(){
testFunction();
}
}
Run Code Online (Sandbox Code Playgroud)
使用以下命令调用上述'b.php':
$method = new ReflectionMethod($this, $method);
$method->invoke();
Run Code Online (Sandbox Code Playgroud)
现在所需的输出是'测试'但接收的输出是NULL.
在此先感谢您的帮助.
您错过了调用函数并删除了protected关键字。
试试这个方法
<?php
$tmp = "testing";
testFunction(); // you missed this
function testFunction(){ //removed protected
global $tmp;
echo($tmp);
}
Run Code Online (Sandbox Code Playgroud)
相同的代码但使用$GLOBALS,会得到相同的输出。
<?php
$tmp = "testing";
testFunction(); // you missed this
function testFunction(){ //removed protected
echo $GLOBALS['tmp'];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9299 次 |
| 最近记录: |