New self vs. new static

前端 未结 3 458
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 10:04

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

3条回答
  •  有刺的猬
    2020-11-22 10:40

    In addition to others' answers :

    static:: will be computed using runtime information.

    That means you can't use static:: in a class property because properties values :

    Must be able to be evaluated at compile time and must not depend on run-time information.

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

    Using self::

    class Foo {
        public $name = self::class;
    
    }
    $Foo = new Foo;
    echo $Foo->name; // Foo
    

    Please note that the Fatal error comment in the code i made doesn't indicate where the error happened, the error happened earlier before the object was instantiated as @Grapestain mentioned in the comments

提交回复
热议问题