首页 > 解决方案 > 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::classTest()函数中的 in 也总是会产生结果。'Foo'Bar::

我知道我可以覆盖其中的Test()函数,Bar但这不是我想要的,我想将实现的功能保留在基本Test()函数中。但只是使用我调用它的实际静态类上下文。

上面的函数有没有办法Test()说“我正在创建一个Bar类型的新实例”并返回一个Bar实例,而不是一个Foo?

标签: phpselfderived-classstatic-classesstatic-functions

解决方案


让我向您介绍后期静态绑定。

考虑以下代码,它与您的代码不完全相同,但它突出显示了我认为您面临的问题。

<?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


推荐阅读