php - PHP:在静态函数中获取派生类上下文?即 BaseClass::staticBaseFunc() 与 DerivedClass::staticBaseFunc() 之间的区别
问题描述
我有一个带有静态函数的基类。但我想有一种方法来了解我在其上下文中调用静态函数的实际类(可能是基类或派生类)。
例如:
<?php
class Foo
{
static function Test()
{
$c = self::class;
echo "Hello, I am creating a new instance of type $c";
return new $c;
}
}
class Bar extends Foo
{
public $someProperty;
}
$b = Bar::Test(); // This should do something different than Foo::Test();
?>
请注意,即使我使用上下文调用它self::class
,Test()
函数中的 in 也总是会产生结果。'Foo'
Bar::
我知道我可以覆盖其中的Test()
函数,Bar
但这不是我想要的,我想将实现的功能保留在基本Test()
函数中。但只是使用我调用它的实际静态类上下文。
上面的函数有没有办法Test()
说“我正在创建一个Bar类型的新实例”并返回一个Bar
实例,而不是一个Foo
?
解决方案
让我向您介绍后期静态绑定。
考虑以下代码,它与您的代码不完全相同,但它突出显示了我认为您面临的问题。
<?php
class A
{
public static $string = 'I am from class A';
public static function getString()
{
return self::$string;
}
}
class B extends A
{
public static $string = 'I am from class B';
}
B::getString(); // returns 'I am from class A' ???!
?>
为了解决这个问题,您可以使用后期静态绑定在运行时上下文中使用变量(而不是在编译时上下文中)
<?php
class A
{
public static $string = 'I am from class A';
public static function getString()
{
return static::$string; // note the change here
}
}
class B extends A
{
public static $string = 'I am from class B';
}
B::getString(); // returns 'I am from class B' and all is well
?>
比我能给你的信息要多得多:https ://www.php.net/manual/en/language.oop5.late-static-bindings.php
推荐阅读
- python - 嵌套循环。如何仅遍历列表中的左、中和右元素?
- flutter - 'bool?' 类型的值 不能分配给“bool”类型的变量
- python - 循环一段时间后重新计算拟合参数
- analytics - DataDog 目录 - 在一台主机上监听多个目录
- java - ANDROID - 如何使用 EditText 进行搜索
- c# - C# for loop dynamodb 添加项目只需添加一行
- kubectl - 使用 yaml 的 kubectl 补丁 - 没有错误,但没有变化
- python - 将叶图保存到栅格
- docker - 在构建 Dockerfile 期间运行“Docker”?
- azure - GitHub PR Merge 不会触发 Azure DevOps Pipeline