LoginSignup
11
10

More than 5 years have passed since last update.

コンストラクタを簡単に書く

Posted at

なんかコンストラクタの書き方を簡単にする新文法が議論中っぽい。

<?php
//こんな風に書けるとドリーム感いっぱい!?
class Point
{
      private $x, $y;      
      public function __construct($this->x, $this->y);
} 

気持ちはわからんでもない。こう、いくつか属性値があるクラスの場合、素直にコンストラクタを作ると代入文が続くので読みにくくなる。。

こういう代入コードは不毛ですよね
<?php
class Foo
{
    private $a,$b,$c,$d;
    function __construct($a, $b, $c, $d)
    {
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;
        $this->d = $d;
    }
}

現状のPHPでこれを多少なりとも簡略化したいなら、get_defined_vars()を使うとよい。

<?php
class Foo
{
    private $a, $b, $c, $d;
    function __construct($a, $b, $c, $d)
    {
        foreach (get_defined_vars() as $key => $val) $this->$key = $val;
    }
}

なお、privateメンバは「_」から始めたいならちょっと加工すればOK。

<?php
class Foo
{
    private $_a, $_b, $_c, $_d;
    function __construct($a, $b, $c, $d)
    {
        foreach (get_defined_vars() as $key => $val) $this->{"_$key"} = $val;
    }
}

ただ、個人的には読みにくいと思ってるし、代入の前に最低限バリデーションすることが多いので、あまり使っていない。

11
10
3

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
11
10