新的自我与新的静态

时间:2011-03-04 17:41:47

标签: php static late-static-binding

我正在转换PHP 5.3库以使用PHP 5.2。阻碍我的方法是使用像return new static($options);这样的后期静态绑定,如果我将其转换为return new self($options),我会得到相同的结果吗?

new selfnew static之间的区别是什么?

3 个答案:

答案 0 :(得分:803)

  

我会得到相同的结果吗?

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

  

new selfnew static之间的区别是什么?

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

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

在以下示例中,B继承了A中的两种方法。 self调用绑定到A,因为它在A的第一个方法的实现中定义,而static绑定到被调用的类(也见{{3} }})。

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

答案 1 :(得分:18)

如果此代码的方法不是静态的,您可以使用get_class($this)在5.2中解决此问题。

class A {
    public function create1() {
        $class = get_class($this);
        return new $class();
    }
    public function create2() {
        return new static();
    }
}

class B extends A {

}

$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));

结果:

string(1) "B"
string(1) "B"

答案 2 :(得分:5)

除了其他人的答案:

  

static ::将使用运行时信息进行计算。

这意味着您不能在类属性中使用lapply,因为属性值:

  

必须能够在编译时进行评估,并且不得依赖于运行时信息。

static::

使用class Foo { public $name = static::class; } $Foo = new Foo; echo $Foo->name; // Fatal error

self::
相关问题