Why return new static? (PHP)

前端 未结 2 483
独厮守ぢ
独厮守ぢ 2021-01-30 17:17

Why some developers create one method that returns new static? What is the reason to have a method that returns new static? I am not asking wha

相关标签:
2条回答
  • 2021-01-30 17:31

    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
    
    0 讨论(0)
  • 2021-01-30 17:36

    new static instantiates a new object from the current class, and works with late static bindings (instantiates the subclass if the class was subclassed, I expect you understand that).

    Having a static method on a class which returns a new instance of same is an alternative constructor. Meaning, typically your constructor is public function __construct, and typically it requires a certain bunch of parameters:

    class Foo {
        public function __construct(BarInterface $bar, array $baz = []) { ... }
    }
    

    Having an alternative constructor allows you to provide different defaults, or convenience shortcuts to instantiate this class without having to supply those specific arguments and/or for being able to provide different arguments which the alternative constructor will convert to the canonical ones:

    class Foo {
    
        public function __construct(BarInterface $bar, array $baz = []) { ... }
    
        public static function fromBarString($bar) {
            return new static(new Bar($bar));
        }
    
        public static function getDefault() {
            return new static(new Bar('baz'), [42]);
        }
    
    }
    

    Now, even though your canonical constructor requires a bunch of complex arguments, you can create a default instance of your class, which will probably be fine for most uses, simply with Foo::getDefault().

    The canonical example in PHP for this is DateTime and DateTime::createFromFormat.

    In your concrete example the alternative constructor doesn't actually do anything, so it's rather superfluous, but I expect that's because it's an incomplete example. If there's indeed an alternative constructor which does nothing other than new static, it's probably just meant as convenience syntax over (new Foo)->, which I find questionable.

    0 讨论(0)
提交回复
热议问题