Why return new static? (PHP)

前端 未结 2 528
独厮守ぢ
独厮守ぢ 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
    

提交回复
热议问题