变量和超全局变量


Variable variables and superglobals

我正在将一个巨大的PHP软件从PHP4转换到PHP5,在我面临的许多(许多)问题中,迄今为止最大的一个似乎是以前的程序员只是沉迷于register_globals功能,时不时地抛出一些变量而不指定源代码,并可耻地将警告和通知隐藏在地毯下。

我试图通过创建一个函数来解决这个问题,该函数在数组上迭代(作为参数传递),并通过"变量"功能创建全局变量,然后在$_POST$_GET$_SESSION的每个页面中调用它。这是代码:

function fix_global_array($array) {
  foreach($array as $key => $value){
    if(!isset($$key)) {
      global $$key;
      $$key = $value;
    }
  }
}

这个函数的问题是条件isset($$key)永远不为真,因此括号内的代码总是被执行并覆盖以前的声明。

这种行为有什么解释吗?我阅读了PHP文档,其中指出

请注意,变量变量不能在函数或类方法中与PHP的Superglobal数组一起使用。

但我不明白这是否与我的问题有关(说实话,我也不明白这意味着什么,我找不到任何例子)。

PS:请不要告诉我使用全局变量和/或变量变量是糟糕的编程,我自己也很清楚,但另一种选择是修改大约2.700个文件,每行1000行代码,我是这里唯一的程序员。。。但是,如果你知道一个更好的解决方案来消除所有那些"未定义变量"的警告,你就可以让我的日子过得很愉快。

PPS:对我的英语也要有耐心^_^

在你给定的代码中,isset($$key)从来都不是真的,因为你在条件检查后调用了global $$key;在向global注册之前,变量不在作用域中。要解决这个问题,只需将该行移动到if-statement上方,这样您的函数将看起来像:

function fix_global_array($array) {
    foreach($array as $key => $value){
        global $$key;
        if(!isset($$key)) {
            $$key = $value;
        }
    }
}

当传递一个数组时,即使该数组是$_POST$_GET,这也可以正常工作。不过,在数组中传递的顺序很重要。如果在$_POST$_GET中定义了索引/键,并且您首先将$_POST传递给函数,则$_GET中的值将不会存储到变量中。

或者,如果您想避免使用可变变量,无论是出于可读性问题还是简单的偏好,您都可以以相同的方式使用$GLOBALS超全局:

function fix_global_array($array) {
    foreach($array as $key => $value){
        if(!isset($GLOBALS[$key])) {
            $GLOBALS[$key] = $value;
        }
    }
}

使用此方法,变量仍然可以访问,就像它们是正常定义的一样。例如:

$data = array('first' => 'one', 'second' => 'two');
fix_global_array($data);
echo $first;    // outputs: one
echo $second;   // outputs: two

此示例适用于上面的两个代码示例。

另外,您还可以使用PHP的extract()函数。它的目的是做fix_global_array()方法所做的事情,甚至有一个覆盖现有变量值的标志。示例用法:

extract($data);
echo $first; // outputs: one

关于extract()的警告,直接适用于这种情况,来自PHP网站:

不要对不可信的数据使用extract(),如用户输入(即$_GET,$_FILES等)。如果您这样做,例如,如果您想运行旧代码暂时依赖register_globals,请确保使用非重写extract_type值,如EXTR_SKIP和注意应该按照中定义的相同顺序提取php.ini中的variables_order。

但是,如果你知道一个更好的解决方案来消除所有那些"未定义变量"的警告,你就可以让我的日子过得很愉快。

有。解决没有使用超全局变量的问题。当然,我并不是说你应该自己手动更改每个翻转变量调用,但我想这可能是你可以自动化的。看看你能不能听从我的想法。

首先,您必须获得所有"未定义变量"通知的列表。这就像注册一个错误处理程序、检查E_NOTICE调用以及检查它是否是未定义的变量调用一样简单。我已经自由地写了一小段代码,正是这样做的。

<?php
/**
 * GlobalsLog is a class which can be used to set an error handler which will 
 * check for undefined variables and checks whether they exist in superglobals.
 * 
 * @author Berry Langerak
 */
class GlobalsLog {
    /**
     * Contains an array of all undefined variables which *are* present in one of the superglobals.
     * 
     * @var array 
     */
    protected $globals;
    /**
     * This contains the order in which to test for presence in the superglobals.
     * 
     * @var array 
     */
    protected $order = array( 'SERVER', 'COOKIE', 'POST', 'GET', 'ENV' );
    /**
     * This is where the undefined variables should be stored in, so we can replace them later.
     * 
     * @var string 
     */
    protected $logfile;
    /**
     * Construct the logger. All undefined variables which are present in one of the superglobals will be stored in $logfile.
     * 
     * @param string $logfile 
     */
    public function __construct( $logfile ) {
        $this->logfile = $logfile;
        set_error_handler( array( $this, 'errorHandler' ), E_NOTICE );
    }
    /**
     * The error handler.
     * 
     * @param int $errno
     * @param string $errstr
     * @param string $errfile
     * @param int $errline
     * @return boolean
     */
    public function errorHandler( $errno, $errstr, $errfile, $errline ) {
        $matches = array( );
        if( preg_match( '~^Undefined variable: (.+)$~', $errstr, $matches ) !== 0 ) {
            foreach( $this->order as $superglobal ) {
                if( $this->hasSuperglobal( $superglobal, $matches[1] ) ) {
                    $this->globals[$errfile][] = array( $matches[1], $superglobal, $errline );
                    return true;
                }
            }
        }
    }
    /**
     * Called upon destruction of the object, and writes the undefined variables to the logfile.
     */
    public function __destruct( ) {
        $globals = array_merge( $this->globals, $this->existing( ) );
        file_put_contents( 
            $this->logfile,
            sprintf( "<?php'nreturn %s;'n", var_export( $globals, true ) )
        );
    }
    /**
     * Gets the undefined variables that were previously discovered, if any.
     * 
     * @return array
     */
    protected function existing( ) {
        if( file_exists( $this->logfile ) ) {
            $globals = require $this->logfile;
            return $globals;
        }
        return array( );
    }
    /**
     * Checks to see if the variable $index exists in the superglobal $superglobal.
     * 
     * @param string $superglobal
     * @param string $index
     * @return bool
     */
    protected function hasSuperglobal( $superglobal, $index ) {
        return array_key_exists( $index, $this->getSuperglobal( $superglobal ) );
    }
    /**
     * Returns the value of the superglobal. This has to be done on each undefined variable, because
     * the session superglobal maybe created *after* GlobalsLogger has been created.
     * 
     * @param string $superglobal
     * @return array
     */
    protected function getSuperglobal( $superglobal ) {
        $globals = array(
            'SERVER' => $_SERVER,
            'COOKIE' => $_COOKIE,
            'POST' => $_POST,
            'GET' => $_GET,
            'ENV' => $_ENV
        );
        return isset( $globals[$superglobal] ) ? $globals[$superglobal] : array( );
    }
}
/**
 * Lastly, instantiate the object, and store all undefined variables that exist
 * in one of the superglobals in a file called "undefined.php", in the same 
 * directory as this file.
 */
$globalslog = new GlobalsLog( __DIR__ . '/undefined.php' );

如果您要在请求的每个页面中包含此文件(可以选择使用php_prepend_file),那么在单击整个应用程序后,您将在"undefined.php"中显示所有未定义的变量。

这是一个非常有趣的信息,因为您现在知道了哪个未定义的变量位于哪个文件中,在哪个行上,以及它实际存在于哪个超全局中。在确定超级全局时,我会记住Environment、Get、Post、Cookie和Server的顺序,以决定哪个优先。

在我们巧妙的小技巧的下一部分中,我们必须遍历所有发现undefined variable通知的文件,并尝试用其超全局对应变量替换未定义的变量。这实际上也很容易,而且,我已经创建了一个脚本来做到这一点:

#!/usr/bin/php
<?php
/**
 * A simple script to replace non globals with their globals counterpart.
 */
$script = array_shift( $argv );
$logfile = array_shift( $argv );
$backup = array_shift( $argv ) === '--backup';
if( $logfile === false || !is_file( $logfile ) || !is_readable( $logfile ) ) {
    print "Usage: php $script <logfile> [--backup].'n";
    exit;
}
$globals = require $logfile;
if( !is_array( $globals ) || count( $globals ) === 0 ) {
    print "No superglobals missing found, nothing to do here.'n";
    exit;
}
$replaced = 0;
/**
 * So we have the files where superglobals are missing, but shouldn't be.
 * Loop through the files.
 */
foreach( $globals as $filename => $variables ) {
    if( !is_file( $filename ) || !is_writable( $filename ) ) {
        print "Can't write to file $filename.'n";
        exit;
    }
    foreach( $variables as $variable ) {
        $lines[$variable[2]] = $variable;
    }
    /**
     * We can write to the file. Read it in, line by line,
     * and see if there's anything to do on that line.
     */
    $fp = fopen( $filename, 'rw+' );
    $i = 0;
    $buffer = '';
    while( $line = fgets( $fp, 1000 ) ) {
        ++$i;
        if( array_key_exists( $i, $lines ) ) {
            $search = sprintf( '$%s', $lines[$i][0] );
            $replace = sprintf( "'$_%s['%s']", $lines[$i][1], $lines[$i][0] );
            $line = str_replace( $search, $replace, $line );
            $replaced ++;
        }
        $buffer .= $line;
    }
    if( $backup ) {
        $backupfile = $filename . '.bck';
        file_put_contents( $backupfile, file_get_contents( $filename ) );
    }
    file_put_contents( $filename, $buffer );
}
echo "Executed $replaced replacements.'n";
unlink( $logfile );

现在,只需要调用这个脚本。我已经测试过了,这就是我测试过的文件:

<?php
require 'logger.php';
$_GET['foo'] = 'This is a value';
$_POST['foo'] = 'This is a value';
$_GET['bar'] = 'test';
function foo( ) {
    echo $foo;
}
foo( );
echo $bar;

有两个未定义的变量($foo$bar),它们都存在于一个(或多个)超全局中。访问浏览器中的页面后,我的日志文件undefined.php中有两个条目;即foo和bar。然后,我运行命令php globalsfix.php undefined.php --backup,它给出了以下输出:

berry@berry-pc:/www/public/globalfix% php globalsfix.php undefined.php --backup
Executed 2 replacements.

好奇结果是什么?我也是。给你:

<?php
require 'logger.php';
$_GET['foo'] = 'This is a value';
$_POST['foo'] = 'This is a value';
$_GET['bar'] = 'test';
function foo( ) {
    echo $_POST['foo'];
}
foo( );
echo $_GET['bar'];

欢呼!没有更多未定义的变量,到目前为止,这些变量正在从正确的超全局变量中读取Big fat免责声明:首先创建备份。此外,这不会立即解决您的所有问题。如果你有一个if( $foo )语句,那么未定义的变量将确保相应的块永远不会被执行,这意味着很可能不是所有的未定义变量都会被一次捕获(但它会在这个脚本的第二次或第三次执行时解决这个问题)。然而这是一个开始"清理"代码库的好地方。

此外,祝贺您阅读我的完整答案。:)