简体   繁体   English

static class scope 在 Z2FEC392304A5C23AC138DA22847F9B7C 是否有任何变化

[英]Is any change in static class scope at PHP 8.1

Today I saw a new type of code execution in PHP that was slightly different from the previous versions.今天在 PHP 中看到了一种新的代码执行类型,与之前的版本略有不同。 The following code is executed as follows from version 8.1 onward.以下代码从 8.1 版本开始执行如下。 Anyone have an idea why?有人知道为什么吗?

<?php

class test {

    /**
     * A test static variable in class
     * @var int $var
     */
    private static int $var;

    /**
     * A method to set value in private variable with name $var
     * @param int $var
     */
    public static function setVar(int $var): void
    {
        self::$var = $var;
    }

    public static function getVar()
    {
        $vars = get_class_vars(__CLASS__);
        echo '<pre>' . print_r($vars, 1) . '</pre>';
    }

}

test::setVar(2);
test::getVar();
test::setVar(3);
test::getVar();

Run result in PHP 8.0.11在 PHP 8.0.11 中运行结果

Array
(
    [var] => 2
)

Array
(
    [var] => 3
)

Run result in PHP 8.1.6在 PHP 8.1.6 中运行结果

Array
(
    [var] => 
)

Array
(
    [var] => 
)

The change is not to static properties themselves, but to the get_class_vars function.更改不是针对 static 属性本身,而是针对get_class_vars function。 The documented purpose of that function has always been to return the default values of all properties, so returning the current value for static properties in previous versions was technically a bug. function 的记录目的一直是返回所有属性的默认值,因此在以前的版本中返回 static 属性的当前值在技术上是一个错误。

To get the current values of static properties, you can instead use the method ReflectionClass::getStaticProperties , eg要获取 static 属性的当前值,您可以改用ReflectionClass::getStaticProperties方法,例如

class Test {
    public static $var = 0;
}

echo "Before:-\n";
echo "Default: "; var_dump( get_class_vars(Test::class) );
echo "Current: "; var_dump( (new ReflectionClass(Test::class))->getStaticProperties() );

test::$var = 42;

echo "After:-\n";
echo "Default: "; var_dump( get_class_vars(Test::class) );
echo "Current: "; var_dump( (new ReflectionClass(Test::class))->getStaticProperties() );

Running this across lots of PHP versions shows that for PHP versions back to 5.5 (and probably beyond, if the syntax of the example is tweaked) the output is (incorrectly):在许多 PHP 版本中运行此程序表明,对于 PHP 版本回到 5.5(如果示例的语法经过调整,可能会更高),output 是(不正确的):

Before:-
Default: array(1) {
  ["var"]=>
  int(0)
}
Current: array(1) {
  ["var"]=>
  int(0)
}
After:-
Default: array(1) {
  ["var"]=>
  int(42)
}
Current: array(1) {
  ["var"]=>
  int(42)
}

For PHP 8.1, it is (correctly):对于 PHP 8.1,它是(正确):

Before:-
Default: array(1) {
  ["var"]=>
  int(0)
}
Current: array(1) {
  ["var"]=>
  int(0)
}
After:-
Default: array(1) {
  ["var"]=>
  int(0)
}
Current: array(1) {
  ["var"]=>
  int(42)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM