Jump to: navigation, search

PHP Array Convert to Class

From w3cyberlearnings

Contents

PHP Array to Class

Convert an array to class object.

Example 1

<?php

class MyClass {

	private $_myvariable;

	public function __construct($properties) {
		$this->_myvariable = $properties;
	}

	// magic methods!
	public function __set($property, $value) {
		return $this->_myvariable[$property] = $value;
	}

	public function __get($property) {
	      return array_key_exists(
		  $property, $this->_myvariable) ? $this->_myvariable[$property] : null
		;
	}

}

$array_class = array(
	 'Basic' => 'PHP',
	 'Advanced' => 'Object Oriented in PHP',
	 'Business' => 'Business System');

$class1 = new MyClass($array_class);

echo $class1->Basic; // display: PHP
echo "<br/>";
$class1->php_salary = 70000;

echo $class1->php_salary; // display: 70000
echo "<br/>";
echo $class1->Business; // Business System
?>

Output

PHP
70000
Business System

Related Links


--PHP Array Introduction-- PHP Access Array-- PHP Array Convert to Object-- PHP Array Convert to JSON-- PHP Array Convert to Class-- PHP Array Convert to String--

Navigation
Web
SQL
MISC
References