OOP in PHP
It’s been a long time since my last post. Sorry for this to all of you who have been looking forward to my next article (yeah, both of you!).
I do like functions. I even try to use functions instead of classes wherever it’s possible - either it’s just because I got used to it by writing PHP for two years (as coding object oriented scripts in PHP 4 was actually impossible), or I’m too stupid to understand the real power of OOP. And even though PHP’s authors have been trying to implement a nice object structure, it still sucks. However, as I consider PHP to be the nicest programming language, I decided to describe its OOP powers.
Why?
Let’s start with the definition of OOP: by using objects, it allows you to keep your code clean and prepared for further development. I suppose you still don’t know what an object is. Think about this: you create a function, let’s call it omg_am_i_pregnant($user), that will check whether the user is pregnant. It actually can return some data, but it’s very difficult to reuse it afterwards. It would probably look like this:
function omg_am_i_pregnant($user) {
if (user_exists($user) && is_pregnant($user)) {
$p = true;
}
}
By doing the same thing with a class called pregnancy, you can easily store the data and send it to, let’s say, a sperm bank.
class Pregnancy {
function __construct($user) {
if (user_exists($user) && is_pregnant($user)) {
$this->p = true;
}
}
}
Now, you may think “WTF are you talking about, the second piece of code is longer and does the same thing”. Yeah, but now, let’s try to check whether Anne, Isabelle and Lucy are pregnant and store the data simultaneously.
$anne = omg_am_i_pregnant('Anne');
$isabelle = omg_am_i_pregnant('Isabelle');
$lucy = omg_am_i_pregnant('Lucy');
The code above won’t work properly, as the function saves the result to the $p variable. Of course, this could be done many other ways, but what if you had to do it this way, using $p?
