Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

php - Best practices for static constructors

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:

new Foo()->set_sth(); // Outputs an error.

So I'm using, if I can call it that, a static constructor:

Foo::construct()->set_sth();

Here's my question:

Is using static constructors like that considered a good practice and if yes, how would you recommend naming the methods for these static constructors?

I've been hesitating over the following options:

Foo::construct();
Foo::create();
Foo::factory()
Foo::Foo();
constructor::Foo();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

<?php

class Duration
{
private $start;
private $end;

// or public depending if you still want to allow direct instantiation
private function __construct($startTimeStamp = null, $endTimestamp = null)
{
   $this->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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...