新自我与新静态 [英] New self vs. new static

查看:105
本文介绍了新自我与新静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在转换一个PHP 5.3库以在PHP 5.2上工作.阻碍我前进的主要因素是使用后期静态绑定(如return new static($options);),如果将其转换为return new self($options),是否可以获得相同的结果?

I am converting a PHP 5.3 library to work on PHP 5.2. The main thing standing in my way is the use of late static binding like return new static($options); , if I convert this to return new self($options) will I get the same results?

new selfnew static有什么区别?

推荐答案

我会得到相同的结果吗?

will I get the same results?

并非如此.不过,我不知道针对PHP 5.2的解决方法.

Not really. I don't know of a workaround for PHP 5.2, though.

new selfnew static有什么区别?

self指的是实际编写new关键字的同一类.

self refers to the same class in which the new keyword is actually written.

static指的是您在层次结构中调用该方法的任何类.

static, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.

在下面的示例中,B继承了A的两个方法. self调用绑定到A,因为它是在A的第一个方法的实现中定义的,而static绑定到被调用的类(另请参见

In the following example, B inherits both methods from A. The self invocation is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see 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

这篇关于新自我与新静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆