gpt4 book ai didi

php - 在类中获取类常量

转载 作者:可可西里 更新时间:2023-11-01 12:50:14 25 4
gpt4 key购买 nike

self::CONSTANT_NAMEstatic::CONSTANT_NAME 有什么区别?

通过 static:: 调用常量是否只有 5.3 功能?

最佳答案

当您使用 static::NAME 时,它是一种称为后期静态绑定(bind)(或 LSB)的功能。有关此功能的更多信息,请访问 LSB 的 php.net 文档页面:http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

一个例子是这个用例:

<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who();
}
}

class B extends A {
public static function who() {
echo __CLASS__;
}
}

B::test();
?>

这会输出 A,这并不总是令人满意的。现在用 static 替换 self 创建这个:

<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}

class B extends A {
public static function who() {
echo __CLASS__;
}
}

B::test();
?>

而且,如您所料,它会输出“B”

关于php - 在类中获取类常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4525893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com