在类之外声明的静态变量

时间:2015-08-18 12:08:12

标签: php codeigniter class variables static

CodeIgniter框架有一个可怕的功能is_php()

/**
* Determines if the current version of PHP is greater then the supplied value
*
* Since there are a few places where we conditionally test for PHP > 5
* we'll set a static variable.
*
* @access   public
* @param    string
* @return   bool    TRUE if the current version is $version or higher
*/
if ( ! function_exists('is_php'))
{
    function is_php($version = '5.0.0')
    {
        static $_is_php;
        $version = (string)$version;

        if ( ! isset($_is_php[$version]))
        {
            $_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
        }

        return $_is_php[$version];
    }
}

请注意,变量$_is_php已定义为static。这个函数没有在任何类中定义,所以我没有看到static定义是正确的语法,即使它(据说)确实具有(假设的)使变量在函数中保持不变的预期效果调用。我在the PHP documentaion中没有看到这种用法。 static关键字的非类使用记录在哪里?这是一个未记录的功能&#39; PHP,可能不受支持,因此不应该依赖它?

1 个答案:

答案 0 :(得分:2)

static变量已在variable scope manual page中定义并记录。

其含义与声明类属性的static关键字略有不同。在这种情况下,static变量只是保留它们的值,即使它们应该超出范围,也不会将它们的范围暴露给外部世界。

相关问题