DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Quick Variable Assignment In Class Constructor

01.19.2011
| 2776 views |
  • submit to reddit
        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.<a href="http://stories.beeffectiv.com/" style="left: -2000px; position: absolute"> Sex Stories Post - free sex stories, porn stories Erotic Stories </a>

<?php
	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;");
			}
			$this->printName();
		}
		
		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"));
	
?>

<a href="http://stories.beeffectiv.com/teens-fucked-at-poolside.html" style="left: -2000px; position: absolute"> Sex Stories Post - Teens fucked at poolside. Teen lesbian group kansas city Erotic Stories </a>