0

クラスを作成するときにこれを行うことがよくありますが、特に 20 個程度のプロパティを持つクラスがある場合は、非常に面倒であることがわかりました。

これを短縮する方法はありますか:

class SomeClass {
    public $property1, $property2, $property3;

    function __construct($property1, $property2, $property3) {
        $this->property1 = $property1;
        $this->property2 = $property2;
        $this->property3 = $property3;
    }
}

思いついたものはすべてググったのですが、結果が見つからなかったので、おそらく不可能でしょうか?

プログラムでそれを行うことができない場合、Eclipse PDT が要求に応じてこのコードを自動的に書き留める方法はありますか?

4

3 に答える 3

1

これをコンストラクタに入れます

$reflector = new ReflectionClass(__CLASS__);
$parameters = $reflector->getMethod(__FUNCTION__)->getParameters();
$variables = get_class_vars(__CLASS__);
foreach($parameters as $parameter)
{
    foreach ($variables as $variable => $value)
    {
        if ($parameter->name == $variable)
        {
            $this->$variable = ${$parameter->name};
            break;
        }
    }
}
于 2012-11-30T03:41:12.817 に答える
0

多分あなたは配列を使うことができます

class SomeClass {
    public $property

    function __construct($property) {
        $this->property = $property;
    }
}
b = new SomeClass(array($property1, $property2, $property3));
于 2012-11-30T03:11:15.957 に答える
0

これがあなたが探しているものだと思います:

class MyTestClass
{
    public $att1, $att2, $att3;

    function __construct($att1, $att2, $att3)
    {
         $class = new ReflectionClass('MyTestClass');
         $construct = $class->getConstructor();
         foreach ($construct->getParameters() as $param)
         {
            $varName = $param->getName();
            $this->$varName = ${$param->getName()};
         }

    }

    function confirm()
    {
        print "att1 = ". $this->att1 . "<br>";
        print "att2 = ". $this->att2 . "<br>";
        print "att3 = ". $this->att3 . "<br>";
    }

}



// Example for non-class functions
function init($a, $b, $c)
{

    $reflector = new ReflectionFunction('init');

    foreach ($reflector->getParameters() as $param) {
        print $param->getName(). " = ".${$param->getName()}."<br>";
    }

}

init ("first", "second", "third");
$testClass = new MyTestClass("fourth", "fifth", "sixth");
$testClass->confirm();

結果:

a = first
b = second
c = third
att1 = fourth
att2 = fifth
att3 = sixth
于 2012-11-30T04:30:34.100 に答える