Object Oriented PHP!
Programming has never been more fun to me till I jumped into Object Oriented Programming, OOP. First, let me explain what it means. OOP, is a programming format that uses Objects (eg. cup, book, car, radio etc) created by the programmer in order to carry out some operations (methods) in his timely programming session.
The normal serial programming most php developers use is reffered to as proceedural programming, something like this.
<?php
$name = “Mukoshy”;
$welcome_msg = “Good Morning”;
echo “$welcome_msg $name“; // Good Morning Mukoshy.
?>
But the question is how many times do you have to echo $welcome.$name on your pages just to tell your visitors a welcome message and as you can see I use Good Morning, what if its Afternoon or even Evening? I’d have to do some if-else statements just to cover the task which will take so much of lines
Even if I accomplish it on one page, I would have to code it (Or Copy) to another page and it goes on all my pages. This has so many disadvantages, from plenty codes for tiny task to tedious work if you decide to change the welcome message to say a uniform one like “Welcome Mukoshy” will serve any time of the day.
So… Let me take it through OOP! See the fun of it.
<?php
class greetings {
function welcome_msg ( $name = ‘User’ ) {
//Now I’d Create the msg (Afternoon, Morning, Evening).
$time_now = time();
if ( date(“A”,$time_now) == “AM” ) {
$msg = “Good Morning”;
}elseif( date (“A”,$time_now) == “PM” && (date(“G”,$time_now)>13)){
$msg = “Good Evening”;
}else{
$msg = “Good Afternoon”;
}
return “$msg $name”;
}
}
?>
Now, I can save this file as greetings.php as my greeting class, all I need to do is call it when I need to say some time greetings to my users, it doesn’t matter how many pages I have I will not have to copy or rewrite the codes again. Simple lines as follow on any page will say the message accordingly.
<?php
include (“greetings.php”);
$greetings = new greetings();
echo $greetings->welcome_msg(“Mukoshy”);
/* The above echo will print, Good Morning Mukoshy if the time is morning OR Good Afternoon Mukoshy if time is afternoon and Good Evening Mukoshy when the time is evening. Simple */
?>
Now you see the power of OOP?
However, I have not taken the time to test the above code…
You debug it if you find some. I just manage to write it and color it. But I’m sure it will serve! (Try It).
OOP simply makes programming easier!
Popularity: 1% [?]


