Leon Anavi
IT Tips && Tricks

PHP

Created: 09.10.2009 23:29 Last Modified: 09.10.2009 23:31 Views: 5619
Keywords: class, encapsulation, magic, object, overload, php5, __get, __set

Time for Magic with __set and __get

The Magic Power of PHP5

PHP5 provides powerful tools for OOP (Object-oriented programming) by adding a lot of new features compared to PHP4. OOP principles encourage encapsulation of class members by declaring them as private or protected and implementation of methods for their management. Usually using getter and setter leads to numerous methods with names like getName(), setName(...), getAge(), setAge(...), etc. Managing and editing all these methods for a class that contains a lot of member can be a difficult and unpleasant task. Here comes the overloading of magic methods introduced by PHP5. Method __get is used to access members and method __set is used to modify their values.

Example Usage

The example demonstrates PHP console application that overloads methods __set and __get inside a class named Magic. Calling an unknown property using __set or __get will lead to an exception which is handled at the catch block.

Source

m_nCounter = 0;
}

public function __destruct()
{
	//Nothing to do
}

public function __get($sName)
{
	switch($sName)
	{
		case "Counter":
			return $this->m_nCounter;
		default:
			throw new Exception("Unknown property.");
	}
}

public function __set($sName, $Value)
{
	switch($sName)
	{
		case "Counter":
			$this->m_nCounter = $Value;
		break;
		default:
			throw new Exception("Unknown property.");
	}
}

}

$Test = new Magic();
try
{
	//call __get
	echo "{$Test->Counter}\n";
	//call __set
	$Test->Counter = 6;
	echo "{$Test->Counter}\n";
	//Next line will throw an exception
	$sTestVar = $Test->Unknown;
}
catch(Exception $ex)
{
	echo "{$ex->getMessage()}\n";
}
?>

Ouput

[leon@localhost phptest]$ php magic.php
0
6
Unknown property.

Further Reading

PHP: Classes and Objects
PHP: Overloading

Class Reference

Class Exception


  Home | About | Contact | Disclaimer | Sitemap 2009-2016 Leon Anavi. All rights reserved.