Best practices for static constructors

后端 未结 8 2460
无人及你
无人及你 2020-12-13 14:41

I want to create an instance of a class and call a method on that instance, in a single line of code.

PHP won\'t allow calling a method on a regular constructor:

8条回答
  •  我在风中等你
    2020-12-13 14:54

    Static constructors (or "named constructors") are only beneficial to prove an intention, as @koen says.

    Since 5.4 though, someting called "dereferencing" appeared, which permits you to inline class instantiation directly with a method call.

    (new MyClass($arg1))->doSomething(); // works with newer versions of php
    

    So, static constructors are only useful if you have multiple ways to instantiate your objects. If you have only one (always the same type of arguments and number of args), there is no need for static constructors.

    But if you have multiple ways of instantiations, then static constructors are very useful, as it avoids to pollute your main constructor with useless argument checking, weakening languages constraints.

    Example:

    start = $startTimestamp;
       $this->end   = $endTimestamp;
    }
    
    public static function fromDateTime(\DateTime $start, \DateTime $end)
    {
        return new self($start->format('U'), $end->format('U'));
    }
    
    public static function oneDayStartingToday()
    {
        $day = new self;
        $day->start = time();
        $day->end = (new \DateTimeImmutable)->modify('+1 day')->format('U');
    
        return $day;
    }
    
    }
    

    As you can see in oneDayStartingToday, the static method can access private fields of the instance! Crazy isn't it ? :)

    For a better explanation, see http://verraes.net/2014/06/named-constructors-in-php/

提交回复
热议问题