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.

1
2
3
4
5
6
7
<?php
	class myClass {
		private $onlyDataMember = 0;
	}
	$classObj = new myClass();
	$classObj->undefinedDataMember = 'Some Value';
	echo $classObj->undefinedDataMember;

The above code will output :

1
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 …

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
	class myClass {
		private $onlyDataMember = 0;
 
		function __set( $dataMemberName, $dataMemberValue ) {
			throw new Exception( "Object property $dataMemberName is not writable!" );
		}
 
		function __get( $dataMemberName ) {
			throw new Exception( "Object property $dataMemberName is not defined!" );
		}
	}
 
	$classObj = new myClass();
	$classObj->undefinedDataMember = 'Some Value';
	echo $classObj->undefinedDataMember;

The output of above code will be :

1
2
3
4
5
<b>Fatal error</b>:  Uncaught exception 'Exception' with message 'Object property undefinedDataMember is not writable!' in <path-to-file>.php:6
Stack trace:
#0 <path-to-file>.php(15): myClass-&gt;__set('undefinedDataMe...', 'Some Value')
#1 {main}
  thrown in <b><path-to-file>.php</b> on line <b>6</b><br />

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
	class myClass {
		private $onlyDataMember = 0;
		private $storageForUndefinedDataMembers = array();
 
		function __set( $dataMemberName, $dataMemberValue ) {
			$this->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 :

1
	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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
	class myDbUsersClass {
		private $recordsArray = array();
 
		function __construct( $fetchThisMuchUsers ) {
			// code for fetching $fetchThisMuchUsers number of records from database and store them to $recordsArray.
		}
 
		function getUsers() {
			return $recordsArray;
		}
	}
 
	$classObj = new myDbUsersClass( 10 );
	$users = $classObj->getUsers();
	foreach( $users as $user ) {
		echo $user[ 'userName' ] . '<br />';
	}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
	class myDbUsersClass {
		private $recordsArray = array();
 
		function __construct( $fetchThisMuchUsers ) {
			// code for fetching $fetchThisMuchUsers number of records from database and store them to $recordsArray.
		}
 
		function __invoke( $onlyArgumentItAccepts ) {
			return $recordsArray;
		}
	}
 
	$classObj = new myDbUsersClass( 10 );
	foreach( $classObj() as $user ) {
		echo $user[ 'userName' ] . '<br />';
	}

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 …

Recently Published

»

Importance and actions of cloud computing in e-commerce business

The e-commerce industry is growing in leaps and bounds, and, ...

»

How to remove Options from One Select Box and retain One Option?

One can easily remove  options of a select box from HTML and append ...

»

How to Ensure that Users Do Not Deactivate The Critical WordPress Plugins

It’s no secret that among all the remarkably useful features of ...

»

How to scroll to the top of a webpage using jQuery ?

If you are looking for an extraordinary method of smoothly scrolling ...

»

11 sources to gain perfect knowledge of html5 semantic tags

1. Html5tuts Html5tuts is a site dedicated to HTML5. Feel free to ...

»

How to move an element into another parent element using jQuery?

An important piece to the puzzle when coding with jQuery is that how ...

»

10 optionally Good WordPress Typography Plugins You could Opt For

It is not necessary that the person will follow the standard guide ...

»

8 creative 3d slider wordpress themes to keep your blog active

1. Display Display is a WordPress Theme best used for Portfolio and ...

»

11 quick remote screen sharing apps worth trying

1. Join Me Easy to start, easy to join, easy to manage, join.me takes ...