LoginSignup
12
7

More than 5 years have passed since last update.

PHPでnewからのメソッドチェーンをできるようにする

Posted at

PHPではnew に続けてメソッドを実行できない。かなしみ。

class Say {
    private $name = 'hoge';
    public function hello () {
        echo "hello {$this->name}";
    }
}
$say = new Say()->hello();
// Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)
//めんどい
$say = new Say();
$say->hello();

自分自身のインスタンスを返す静的メソッドを用意しておくとそれに続けてチェーンできる。

class Say2 {
    private $name = 'hoge';
    public static function forge() {
        return new static;
    }
    public function hello () {
        echo "hello {$this->name}";
    }
}
Say2::forge()->hello();

ちなみにnew クラス名をカッコで囲ってもチェーンできる。

(new Say())->hello();
// hello hoge
12
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7