在 PHPUnit 运行的函数中访问时的全局变量 null

Global variable null when accessed in function run by PHPUnit

提问人:Jodes 提问时间:5/3/2023 更新时间:6/24/2023 访问量:61

问:

这应该是一件非常简单的事情。

我有以下内容:dbconnect.php

<?php

var_dump($config); // this works! 

function dbconnect($conf = null){
    global $dbconn, $config;

    var_dump($config); // null!

    $config = $conf??$config;
    // A hack to get it working on PHPUnit. For some reason the global variable
    // config is coming in as null

    $dbconn = mysqli_connect(
        $config['dbHost'], $config['dbUser'], $config['dbPass'], $config['dbName']);

    if ($dbconn -> connect_errno) {
      fault("MySQL", "Failed to connect: " . $dbconn -> connect_error);
      exit();
    }   
}

?>

从注释中可以看出,正在作为 null 访问,即使它在 :$configconfig.php

<?php

$config = array();
$config['local']['dbHost'] = 'localhost';
$config['local']['dbName'] = 'logicsmith';
$config['local']['dbUser'] = 'root';
$config['local']['dbPass'] = '*******';

// ... other stuff here

$transferToConfig = ['dbHost', 'dbName', 'dbUser', 'dbPass'];

foreach ($transferToConfig as $name)
    $config[$name] = $config['local'][$name];

// ... other stuff here

?>

只有当我在 Windows 的命令行上通过 PHPUnit 运行时才会发生这种情况(这是命令):

php phpunit.phar .\commonTests --testdox --stderr

测试文件的开头有以下内容:FaultsTest.php

<?php

use PHPUnit\Framework\TestCase;

// ... other stuff here

$configFile = 'C:\wamp2\www\commonTests\includes\config.php';
require 'common/includes/start.php';

// TestCase class here

?>

并具有以下特点:start.php

// ... other stuff here

$configFileToUse = $configFile??__DIR__."/config.php";
require_once($configFileToUse);

// .. other stuff here

require_once(__DIR__."/dbconnect.php");

// ... other stuff here

if (!($bypassDbConnect??''))
{
    dbconnect($config);
    // ... other stuff here
}

请记住,当我包含在我从 WAMP 或我的实时 linux 服务器访问的页面中时,它可以正常工作。start.php

哪里出了问题?我该如何解决?我宁愿使用全局变量,也不必将它们传递给每个需要它们的函数。

谢谢

php 命令行 null phpunit 全局变量

评论


答:

0赞 aksuska 6/24/2023 #1

我在升级 PHPUnit 时遇到了类似的问题。我发现 PHPUnit 将所有内容加载到本地作用域中,包括引导文件(如果使用),它曾经是一个全局作用域。我必须在$GLOBALS超全局中明确定义全局变量,以便它们在 PHPUnit 下工作。在您的例子中,这意味着使用 $GLOBALS[“config”] 而不是 config.php 中的 $config。