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

June 25th, 2011 - 

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

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 :

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 …

12345678910111213141516undefinedDataMember = ‘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:6Stack 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.

123456789101112131415161718192021storageForUndefinedDataMembers[ $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 :

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.

123456789101112131415161718getUsers();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 …

1234567891011121314151617‘;}

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 …

View the original article here

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

June 24th, 2011 - 

Continuing my posts on PHP Magic Functions lets close this topic now and talk about rest of the Magic Functions.

Before talking about these magic functions, I want you to be clear about serialization and unserialization of a variable. Some times you need to ( may be you’ve never done so but now you’ll atleast think about it ) store ( using string representation ) your variable to database or primary storage or session or any where and from that location you can get the same value again.

To acheive this you can use either of two available possiblilities in PHP. First one is use of serialize and unserialize functions and another one is use of json_encode and json_decode functions. I personally prefer the formar approach since serialize and unserialize functions are quite faster than json_encode and json_decode functions. The latter approach is useful when you need to port your data from php to other programming languages like javascript or actionscript etc.

Have take a look, what I’m talking about …

12345678910111213141516If you call serialize function on an object then it checks first whether there you’ve written __sleep magic function or not in your class. If you’ve then that function gets executed and the return value of the function is serialized or the object itself gets serialized. Now think where it can be useful. Suppose you’ve a class that connects you to the mysql database and stores basic information required for that ( host, user name, password ) then you’ll never wish to serialize your object along with your secret informations ( password in this case ). In that case you can employee the __sleep magic function and choose which values you want to export from the object. Lets see how I’ll code my database connect class …

12345678910111213141516171819connect();var_dump( serialize( $connectToDb ) );

The above snippet of code will output something like this …

string(156) “O:9:”ConnectDb”:3:{s:20:”ConnectDb_hostName”;s:9:”localhost”;s:20:”ConnectDb_userName”;s:9:”mysqluser”;s:22:”ConnectDb_selectedDb”;s:10:”my_blog_db”;}”

View the original article here

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

June 23rd, 2011 - 

There are some reserved function names  in PHP class starting with __ ( double underscore ). These are __construct, __destruct, __isset, __unset, __call, __callStatic, __sleep, __wakeup, __get, __set, __toString, __set_state, __invoke and __clone. You cannot use these functions to serve your logical purpose but these are meant to be used for providing magic functionality.

Lets start with the most familiar ones …

These methods are better known as constructor ( called when object is initialized ) and destructor ( called when object is destroyed or scope of an object vanishes ), well known keywords in Object Oriented Programming. Most of you guys are already familiar with these functions therefore I am not going to discuss them in detail.

There are two ways of calling a class function. First one is with Object Scope and second one is with Static Scope. In former case an object of the class is first instantiated and then a function is called using the -> ( I’m missing its name, any suggestion !!! ) operator while in latter case the function is called using the Scope Resolution Operator( :: ) with class name.

Whenever you try to access a function of your class with object scope which is not defined it throws an error. e. g.

showValue();

This will throw an error on execution:

Fatal error: Call to undefined method myClass::showValue() in .php on line 11

To avoid this you can use magic function __call, this function is called whenever an undefined function of a class is called with object scope. Lets have a look

steve(); $sayHello->adams(); $sayHello->dexter();

The output of the above code will be :

Hello Steve !!!Hello Adams !!!Hello Dexter !!!

Now think what will happen, if we call an undefined function with static scope, this will again throw an error on execution. To handle call to undefined static functions the __callStatic magic function is used.

The output of the above code will be same as it was for the former code :

Hello Steve !!!Hello Adams !!!Hello Dexter !!!

For rest of the magic functions keep visiting my blog and don’t forget to leave feedback about the the post.

Happy coding and keep it as simple as possible.

View the original article here