jeudi 30 juillet 2015

(PHP Reflection?) Create a new instance of a type hint given as parameter

Take a moment and look at these two simple classes:

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(){ ... }
    // ...
}

Here's what I'm trying to do:

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

// I have the setter method name
$setter = "setAddress";  

// 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? 
?????

I suppose I need to use some form of Reflection? (Also, I hear Reflection can have slow performance, so feel free to recommend any better performing approach if you know of one.)





Aucun commentaire:

Enregistrer un commentaire