phpphp-7type-hintingphp-7.1late-static-binding

How to indicate in php 7.1 that the return type is the current child type?


I have

abstract class A{
  public static function getSingle($where = []) {
    $classname = get_called_class();

    $record =     static::turnTheWhereIntoArecordFromDB($where);
    $model = new  $classname($record);
    return $model;
  }
}

class B extends A{

}


$x = B::getSingle();

$x has no type hinting... I like type hinting, so I want type hinting for B, not for A

How to enable type hinting directly for $x?

what I thought is something like

 public function getSingle($where = []) : ?get_called_class()

This obviously doesn't work

Is there something that does?


Solution

  • For the example you present, why do you need to have a factory method? You are creating a new instance from the constructor, why don't you just $x = new B($record)!

    UPDATED ABOVE


    abstract class A
    {
        /**
         * @param array $where
         * @return static
         */
        public static function getSingle($where = [])
        {
            $classname = get_called_class();
    
            $model = new  $classname($record);
            return $model;
        }
    }
    

    @return static will type hinting its child class. Also I changed your function to static function, it is typical factory pattern.