PHP Magic Functions: Best Part of Object Oriented PHP – Part 2


In my previous post ( PHP Magic Functions ), I discussed about __construct, __destruct, __call and __callStatic. Lets explore a few more magic functions …

__set and __get : Define Object Data Members at Run Time

In PHP what happens when you try to write data to an undefined object data member. PHP doesn’t throw any error or warning or exception. You can easily write and access that data member in your code. For e.g.

undefinedDataMember = 'Some Value';
	echo $classObj->undefinedDataMember;

The above code will output :

Some Value

In case, you want to take some action on access to undefined data member, you’ll have to write __set and __get functions in your class. You may want to throw an exception for alerting user not to do so or you may want that this undefined data member should be stored to some other place ( predefined array or something ).

Lets have a look …

undefinedDataMember = 'Some Value';
	echo $classObj->undefinedDataMember;

The output of above code will be :

Fatal error:  Uncaught exception 'Exception' with message 'Object property undefinedDataMember is not writable!' in .php:6
Stack trace:
#0 .php(15): myClass->__set('undefinedDataMe...', 'Some Value')
#1 {main}
  thrown in .php on line 6

Another case is when you wish to store such writes to some other location. e.g.

storageForUndefinedDataMembers[ $dataMemberName ] = $dataMemberValue;

		function __get( $dataMemberName ) {
			if( isset( $this->storageForUndefinedDataMembers[ $dataMemberName ] ) ) {
				return $this->storageForUndefinedDataMembers[ $dataMemberName ];
			} else {
				throw new Exception( "Object property $dataMemberName is not defined!" );

	$classObj = new myClass();
	$classObj->undefinedDataMember = 'Some Value';
	echo $classObj->undefinedDataMember;

The above code will output :

	Some Value

__invoke : Object as Function

This is one of the magic functions that I feel good to use. Some times you just need to access an array from the object and use that in your code. e.g.

	foreach( $users as $user ) {
		echo $user[ 'userName' ] . '
'; }

The above code will output names of users from database. Now lets use PHP’s magic functionality in this piece of code …


Note the change in foreach line I’ve used the object as function and this will solve the same purpose.

I’ll keep discussing about rest of the Magic Functions in my future posts.

Before packing up things for today, one tip for programmers only : Always try to use friendly variable names ( i.e. Just name of variable clears the purpose of that variable to any reader ) for Self Explanatory Code.

Enjoy the magical PHP and happy coding …

  • May 9, 2011
8 Best Free Stock Video Websites for Tiktok, Reels, and Shorts Top 5 PHP Frameworks: Fast and Secure