PHP: call child constructor from static method in parent

前端 未结 4 1819
天命终不由人
天命终不由人 2021-01-17 17:45

I want to have a static method in a parent class that creates instances of whatever subclass i call this method on.

An example to make this more clear:

cl         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-17 18:00

    As of php 5.3 you can use the static keyword for this

    prints

    object(A)#1 (0) {
    }
    object(B)#2 (0) {
    }
    object(C)#1 (0) {
    }
    

    edit: another (similar) example

    prints

    t=A
     A::__construct
      type of o=A
    t=B
     B::__construct
      type of o=B
    t=C
     C::__construct
      type of o=C
    

提交回复
热议问题