php - 新 self 与新静态

我正在转换 PHP 5.3 库以在 PHP 5.2 上运行。阻碍我的主要事情是使用后期静态绑定(bind),如 return new static($options); ,如果我将其转换为 return new self($options)我会得到相同的结果吗?

new selfnew static有什么区别?

最佳答案

will I get the same results?

不是真的。不过,我不知道 PHP 5.2 的解决方法。

What is the difference between new self and new static?

self 指的是实际写入 new 关键字的类。

static,在 PHP 5.3 的后期静态绑定(bind)中,指的是层次结构中您调用该方法的任何类。

在以下示例中,BA 继承了这两个方法。 self 调用绑定(bind)到 A 因为它是在 A 的第一个方法的实现中定义的,而 static绑定(bind)到被调用的类(另见 get_called_class() )。

class A {
    public static function get_self() {
        return new self();
    }

    public static function get_static() {
        return new static();
    }
}

class B extends A {}

echo get_class(B::get_self());  // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A

https://stackoverflow.com/questions/5197300/

相关文章:

php - PHP 中的 NOW() 函数

php - 如何在 PHP 中向空数组添加元素?

php - 为什么这段代码不简单地打印字母 A 到 Z?

php - 在 PHP 中将整数转换为字符串

php - 在 PHP 中的任意位置插入数组中的新项目

php - 按一个属性对对象数组进行排序

php - 不能在写上下文中使用方法返回值

php - 如何在 PHP 中获取字符串的最后一个字符?

php - 如何在 PHP 中执行静态代码分析?

php - 如何找到foreach索引?