Quick variable assignment in class constructor

Submitted by:Jessey Ryder

Date added:19 January, 2011


When creating a new object, pass the initial variables as an array. Then use this code to quickly assign the array vars to the class vars. This will mean importing large arrays into the object in three lines of code.

Tags: php , variable , class

Code Snippet:

class person {
private $first_name, $middle_name, $surname;

public function __construct($details = array()) {
foreach ($details as $key => $data) {
# Don't forget the ';' at the end of the statement inside eval()
eval("\$this->$key = \$data;");

public function printName() {
print("{$this->first_name} {$this->middle_name} {$this->surname}\n");

$greg = new person(array("first_name" => "Gregory", "middle_name" => "Alexandra", "surname" => "Peck"));