编程

PHP 8.3: get_class() 和 get_parent_class() 函数弃用不带参数调用

358 2023-10-31 23:30:00

PHP 8.3 弃用多个支持多个签名的函数及类方法。历史上,这些函数最初只接受一个函数签名,不过在后来的版本中在不声明新函数情况下支持另一套参数。

get_classget_parent_class 函数也是支持两个签名的函数。

两个函数都接受 object $object 参数,并返回其类名,或者其父类名(get_parent_class 函数)。

get_class(new stdClass()); // "stdClass"
get_parent_class(new \InvalidArgumentException()); // "LogicException"

不过,它也支持另外一种签名,即不传参数,它根据上下文 context 返回类名。

class MyException extends InvalidArgumentException {
    public function __construct() {
        get_class(); // "MyException"
        get_parent_class(); // "InvalidArgumentException"
    }
}

PHP 8.3 中,不带参数调用 get_classget_parent_class 函数将被弃用。上述代码在 PHP 8.3 中发出了弃用通知。在 PHP 9.0 中,z这个签名重载将被移除,这将导致 ArgumentCountError 异常,除非传递了 object $object参数。 

Deprecated: Calling get_class() without arguments is deprecated
Deprecated: Calling get_parent_class() without arguments is deprecated

get_class() 替换

当前 get_class() 函数只允许在类上下文中调用,弃用的 get_class 调用可以使用 self::class 或者 __CLASS__ 常量替换。self::class 魔术常量在 PHP 5.4 及之后的版本中都是可用的。__CLASS__ 常量自 PHP 5.0 以后的版本可用。

class Test {
    public function __construct() {
-       echo get_class();
+       echo __CLASS__;
    }
}

此外,将 $this 传递给 get_class 函数也可以避免弃用通知,并同时保留 get_class 调用。PHP 5.0 以后的版本都支持此种方式。

class Test {
    public function __construct() {
-       echo get_class();
+       echo get_class($this);
    }
}

PHP 8.0 以后支持 $object::class 
自 PHP 8.0 其,::class 魔术常量也支持对象调用。在 PHP 8.0 应用中,get_class 的调用可用使用 $object::class 安全替代。

- get_class($object);
+ $object::class

替换 get_parent_class()

不带参数调用 get_parent_class() 返回的值与 `parent::class` 魔术常量一样。这个函数调用可以使用 parent::class 常量替换。

类似于 get_class 替换,请传入 $this 到 get_parent_class()。不过该行为与 get_parent_class 不同,因为如果没有父类而使用 parent 会导致致命错误。  
class Test extends BaseTest{
    public function __construct() {
-       echo get_parent_class();
+       echo parent::class;
    }
}

要模仿 get_parent_class() 行为使之没有弃用声明,请将 $this 传入到该函数中:

class Test extends BaseTest{
    public function __construct() {
-       echo get_parent_class();
+       echo get_parent_class($this);
    }
}

向后兼容性影响

PHP 8.3 弃用不带参数调用 get_classget_parent_class 函数。这是为了准备使 PHP 的代码库不支持重载的替代函数签名。

get_classget_parent_class 调用可以使用向后兼容的替代方案来避免弃用通知。