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 回答