根据大多数编程语言范围规则,我可以访问在其中的函数外部定义的变量,但为什么这段代码不起作用?
<?php
$data = 'My data';
function menugen(){
echo "[".$data."]";
}
menugen();
?>
Run Code Online (Sandbox Code Playgroud)
有[]输出.
我正在学习和探索PHP 5.2.9的PHPUnit应用程序,并遇到了全局问题.我已将$ backupGlobals设置为FALSE,包括文档'@backupGlobals disabled',这似乎不会影响PHPUnit备份全局变量的行为.有什么我想念的吗?我需要更改PHPUnit的xml文件吗?创建一个引导程序?
config.php文件:
$testString = 'Hello world!';
Run Code Online (Sandbox Code Playgroud)
basicApp.php:
require ('D:\data\clients\security.ca\web_sites\QRASystems.com\wwwroot\__tests\BasicApp\config.php');
class BasicApp {
public $test;
public function __construct() {
global $testString;
$this->test = $testString;
}
public function getTest() {
return $this->test;
}
public function setTest($test){
$this->test = $test;
}
Run Code Online (Sandbox Code Playgroud)
BasicAppTest.php:
require ('D:\data\clients\security.ca\web_sites\QRASystems.com\wwwroot\__tests\BasicApp\BasicApp.php');
class BasicAppTest extends PHPUnit_Framework_TestCase{
protected $testClass;
protected $backupGlobals = FALSE;
protected $backupGlobalsBlacklist = array('testString');
public function SetUp(){
$this->testClass = new BasicApp;
$this->testClass->bootstrap();
}
public function testGlobal(){
echo $this->testClass->getTest();
$this->assertNotNull($this->backupGlobals);
$this->assertFalse($this->backupGlobals);
$this->assertNotEmpty($this->testClass->test);
}
public function testMethods(){
$this->testClass->setTest('Goodbye …Run Code Online (Sandbox Code Playgroud) 在我的代码中,我有一个初始化MySQLi类的文件.
File a:
$db = new Database(); //MySQLi class
Run Code Online (Sandbox Code Playgroud)
无论如何,有一个包含此数据库类的文件.该文件还包括其中声明了函数的其他文件.我正在global联系$db
File b:
function xy(){
global $db;
$sql = "..."
return $db->getArray($sql);
}
Run Code Online (Sandbox Code Playgroud)
Testfile:
require "file_a.php";
require "file_b.php";
require_once "PHPUnit/Framework/TestCase.php";
class testProblemStatistics extends PHPUnit_Framework_TestCase {
testArray(){
$this->assertTrue(array_key_exists('xy', $this->xy())
}
}
Run Code Online (Sandbox Code Playgroud)
我得到:
致命错误:在非对象上调用成员函数getArray()
我调查过:
var_dump($db);
function xy(){
global $db;
var_dump($db);
...
}
Run Code Online (Sandbox Code Playgroud)
第一个转储给了我MySQLi对象,
第二个转储给了我NULL
file_b中的全局变量有问题.
附加信息:我正在使用PHPUnit,我在命令提示符下运行它.在普通浏览器中一切正常.