New self vs. new static

前端 未结 3 494
伪装坚强ぢ
伪装坚强ぢ 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:34

    If the method of this code is not static, you can get a work-around in 5.2 by using get_class($this).

    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()));
    

    The results:

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

提交回复
热议问题