(PHP Reflection?)创建一个类型提示的新实例,作为参数

时间:2015-07-30 21:41:14

标签: php reflection

花点时间看看这两个简单的类:

use ValueObjects\Address;

class Person {

    private $address;

    public function setAddress(Address $address){
        $this->address = $address;
    }
}

class Address {
    private $line1 = "";
    private $line2 = "";
    private $city = "";
    private $state = "";
    private $zip = "";

    public function __construct($line1, $line2, $city, $state, $zip){
        $this->line1 = $line1;
        $this->line2 = $line2;
        $this->city = $city;
        $this->state = $state;
        $this->zip = $zip;
    }

    public function getLine1(){ ... }
    public function getLine2(){ ... }
    // ...
}

这是我正在尝试做的事情:

// I have the class instance
$person = new Person();  

// I have the setter method name "setAddress"
$setter = "set".ucfirst("address");

// I have these parameters
$line1 = "123 Main St.";  
$line2 = "";
$city = "New York";
$state = "NY";
$zip = "10000";

// I only have the information you see above, how do I use that to set
// these values into $person? 
?????

我想我需要使用某种形式的反射? (另外,我听说Reflection可能性能很慢,所以如果你知道的话,可以随意推荐任何更好的方法。)

2 个答案:

答案 0 :(得分:0)

我只想更改构造函数以接受键值数组。类似的东西:

public function __construct($array){
 foreach ( $array as $key => $value ) {
    $this->$key = $value;
  }
}

然后,不要设置变量,在数组中设置键。如

$data = array( 
'line1' => "123 Main St.",
'line2' => "",
'city' => "New York",
'state' => "NY",
'zip' => "10000",
);

我倾向于只实现松散类型的函数,而不是使用大量的反射。例如:

<?php

class Person {

    private $address;

    public function setAddress(Address $address){
        $this->address = $address;
    }

    // loosely typed setter
    public function _setAddress($data){
        $this->address = new Address($data);
    }
}

class Address {

    private $line1 = "";
    private $line2 = "";
    private $city = "";
    private $state = "";
    private $zip = "";

    public function __construct($array){
     foreach ( $array as $key => $value ) {
        $this->$key = $value;
      }
    }
}

$p = new Person();

$setter = "_setAddress";
$data = array(
    'line1' => "123 Main St.",
    'line2' => "",
    'city' => "New York",
    'state' => "NY",
    'zip' => "10000",
);

$p->$setter($data);

print_r($p);

否则,如果你使用反射(可能会更慢),那就是:

How do I get the type of constructor parameter via reflection?

答案 1 :(得分:0)

我确定最好的解决方案是避免反射,而是构建某种自动映射器。你可以看到Jimmy Bogard完成了something like this in .net。 PHP没有指定的返回类型,但我认为我以某种方式解决了这个问题。