PHP, OOP and Head Explosion
Written By dreamweaver on Nov. 19, 2007.
21 Comments
Report Note
+ Clip This
Somebody please tell me that OOP does eventually make some sort of sense after you work with it awhile. I'm taking a PHP class, and half of this evening's session was about OOP, and though this is not the first time I've tried to understand it, I still don't get it really. I had to look at the sample code solution from the instructor to even get the problem worked out on this one. GAAAAA!!!
If you have any pointers, or if you can remember something that someone said to you or that you read somewhere that made a light bulb go on about the whole OOP thing, please share! I'm going to pick up the pieces of my brain off the floor now and take myself off to bed, and check back in the morning in hopes of seeing some magic words of wisdom.
Oh, by the way, is there an emoticon for "head explosion"?? No wonder I have a headache! :/

Mike
Written Nov. 19, 2007 / Report /
Meh, I don't really code PHP in an object-oriented way basically because OOP functionalities were tacked on after the language was developed. I learned Java (not Javascript) in an OOP-manner because the whole language is object-oriented, but PHP is more of a scripting language with some OOP functionalities grafted onto it. I'm sure that there are performance and architectural values to OOP PHP code but I don't see enough value to have me stop coding how I do and move all my PHP code to object-oriented styles.
I don't know how OOP with PHP really works, but OOP coding allows you to build your own classes and objects and work with them as if they're like other variables types you'd use like numbers or strings. Basically you define the class and then define various functions and variables within the class. In Java, you'd instantiate an object and normally pass it some type of variable in the constructor that it'd use to create that object. If I want to create a new User object with "Mike" as the constructor variable, I'd pass it over and then the User class would take "Mike" and do things to it and let me work with "Mike the user" as one big, self-contained, thing, instead of having spaghetti code all over that I may have to duplicate in order to do what I want. Then I work with a User object and ask the User object do do things and everything is wrapped up nicely in my code. I don't have to worry about where user functionality is because if you code it correctly it's all nicely tucked inside my User class. If I want to give users some new functionality I'd add new functions into my User class and then wherever I use the User object within the rest of my code, I can then use the new functionality there as well.
I'm sure other people at 9rules can more eloquently explain OOP than me :)
ericwindham
Written Nov. 19, 2007 / Report /
Easy answer
You have a block of code, say 100 lines or so that you use a lot. Make a class for it.
class someClass {function blockOfCode {
block of code goes here...
}
}
var a = new someClass();
a->blockOfCode;
There you just reduced 100 lines of code to two. OOP is much more powerful, but that's an easy example.
And don't worry. It was my senior year in college when I was working on a project involving OOP, and all of the sudden it hit me. "OOOOOOOOOOOhhhh!" That's what OOP can do.
Ozone42
Written Nov. 19, 2007 / Report /
OOP Is just organization. People will argue against that, but when it comes down to it you're doing the same things you did back in procedural programming, it just forces you to organize it in a more organic way.
Here's how I think of it. A class is kind of like a living creature. Everything that class needs to do is contained within it's biology. If it needs to eat, it has an eat method/function. If it needs to breathe, etc.
Now say you have a need for other little critters that do basically the same thing, with a few adjustments, enhancements, or something along those lines. That's where inheritance comes in. You now get things that take the same basic "species" and enhance it a bit with new methods, and retain the old.
Now you get into the main flow of the program (which is still basically procedural, perhaps with some events mixed in,) you decide how many of what critters you need, instantiate them, have them call their events or functions, and poof, you've got a program (or ecosystem?)
I use the object oriented bits in php nowadays, but it's just for organization and modularization. I could do the same thing with non OO stuff, it'd just be a bit messier.
Mike
Written Nov. 20, 2007 / Report /
Yeah you guys killed my explanation.... good stuff!
Oli
Written Nov. 20, 2007 / Report /
OOP is mother. OOP is father. Trust OOP. </bablyon5>
That said, PHP's hack-n-slash implementation of OOP leaves a lot to be desired and I wouldn't wish learning OOP in PHP on my greatest enemy. You've got no real choice in the matter, so lets give this a go...
To try and understand this, try to imagine objects are real life objects. A car for example. You create a blueprint for what a car should do - a class. You say that you want three functions: accelerate, brake and steer. There are also variables like current speed, direction.
Then, using this blueprint, you create a car. In OOP this is called an instance:
$car1 = new Car();Then we want to accelerate 10mph:
$car1->accelerate(10);Brake to stopped:
$car1.brake(10);This side of things isn't too difficult once you can understand instances, what will really boil your noggin is inheritance =) I'll go into it now because this is one of the biggest code-saving, pain-saving devices OOP has to offer you.
Imagine we need to make blueprints for cars, trucks and vans. The three functions apply to all of these, so it's silly to put the same code into each of these blueprints, doesn't it?
Therefore we can make an abstract class (something that wouldn't make sense to create an instance of) that covers this core functionality. Lets call it Vehicle and give it the functions that used to be in Car. For our new blueprints, we "inherit" Vehicle:
class Car extends VehicleetcWhat this means is when you have an instance of Car, you've access to everything in Vehicle.
To mush things up, you can also pass things backwards and forwards between Car and Vehicle. To make sense of this, just think how not all vehicles accelerate the same way. So say Vehicle has an $acelerationRate variable, we can override this from inside Car, so that when we accelerate an instance of Car, it uses the overridden value instead of Vehicle version.
OOP makes a lot of very logical sense for a great number of applications, it's just a lot of unfamiliar things jumping you all at once. Just take it back to simple ideas and you can digest it quite easily.
cpoteet
Written Nov. 20, 2007 / Report /
These are good explanations. I learned the most about OOP at my job doing C#. I really learned the power of OO when we started refactoring into our n-tier architecture (similar to the MVC architecture).
dreamweaver
Written Nov. 20, 2007 / Report /
Ah, I knew there'd be some people here with some good explanations. After sleeping off the headache and reading all the good stuff here, this is my conclusion:
I understand the overall theory, and what OOP is supposed to do (I think!), BUT I get lost with the terminology (instantiate, constructor, etc.) and possibly the scope, and the syntax. I know this probably all means that I need to just study it and use it more, which leads to the second problem: maybe I haven't run across anything in my own personal work that OOP would have made easier.
I vaguely remember my head exploding over multidimensional arrays, and when I was learning about arrays I just thought "okay, that doesn't make sense right now, maybe it will later" and moved on. Then the light bulb finally went on when using a multidimensional array seemed to be the only way to make the code function as needed. Maybe OOP will be the same for me? Except that what I'm seeing is that OOP is optional, and something that you use to make it all easier*, and everything OOP can do, can be done without OOP.
*"easier" is entirely dependent on your point of view, and whether your head has exploded yet, and whether you're trying to deal with "inheritance" as Oli was talking about. My brain started to go all mushy again at that one, so I'll come back to that later. ;)
Another part of the problem with all this may be that I don't have a programming background at all. I've taught myself PHP (and everything else web related, really) by reading and working with it, and when you do that there tends to be holes and gaps in your knowlege. You can sail a leaky boat for a while, but eventually you either plug the holes or sink. Some things in this "beginner" class are super easy for me, and some things just make no sense at all.
Thanks to all of you! I really appreciate all the input and the examples and explanations; I'm bookmarking this Note, so I can come back to it as a reference!
Oli
Written Nov. 20, 2007 / Report /
OOP definitely lends itself more readily to larger projects where you have multiple things that you could envisage as objects. This is key because a lot of time is spent in data-design, working out the most logical object structure.
The CMS I made for my site is entirely OOP and in order to do that, I had to work out what, in effect, makes up a blog. Here's my basic object structure, from the top:
So it's a data-structure, effectively. Every 4 hours my site calls the Site constructor, which loads all the Types and Sections and then gets all the PostLinks and throws them in the correct Section-instances. That instance of Site is thrown into RAM and then my front-end logic can use it to pull out a post or a whole thread and display it. It maps my database design almost 1-for-1, it just has a lot more logic so that I can use the data in context without having to do any database interaction in whatever front-end I wanted.
I also use Objects for the front-end in a MVC context. These are a butt-load more difficult to explain (hence I gave a description of my data-structure) because they're pretty intricate and inherit a *lot* from the framework (.NET in my case)
Oli
Written Nov. 20, 2007 / Report /
I should add:
There's 1 instance of Site, with multiple instances of Type.
Each Type has multiple instances of Section.
Each Section has multiple instances of PostLink.
And each PostLink has multiple instances of Post.
A beautiful tree.
And my point of dragging you through 2 years of data-design: Try and imagine storing that sort of data linearly.
It's like an array inside an array, inside an array (etc) apart from each value at every level has functionality. I can poke an instance of Post and find out what section it's in (by finding its parent PostLink and asking that what Section it belongs in). From Type-level I can see who has made the most Posts. I can add a new Post to a section and it knows what Type it's in and the Type knows to display it when asked for a list from the front-end.
There is also inheritance in this structure (they all inherit the same class) which allows me to say "This Post has updated" and that tells the PostLink it has changed, and that tells the Section it has changed, and that tells ... all the way up to the Site, where I can bind "event listeners" so I know I need to flush a certain cache (like needing to regenerate the RSS feeds, or email users (if they want updates on a Post/thread/Section/Type). It's massively complex but it's also massively convenient.
dreamweaver
Written Nov. 20, 2007 / Report /
Oli, you've just made my head explode AGAIN. When I get my head put back together, and wrapped around OOP in a small way, I'll come back to your "massively complex" example! :)
anadgouda
Written Nov. 20, 2007 / Report /
OOP is a way of thinking more than anything else. You are trying to build a system with entities that interact with each other. Thought there are OOP languages, the syntax support is not a must. One of the best examples of OOP in PHP is Drupal code. Some thoughts on my blog.
One thing I realized while teaching OOP was that its benefits cannot be explained using trivial examples. In fact it is not suitable for simpler tasks, the cost-benefit analysis goes against it. But take a real world problem, try to design in the flexibility and stability you want and you will see the benefits of OOP.
Oli
Written Nov. 20, 2007 / Report /
Sorry I thought it might bea easier to understand as an improved data-structure... but I got carried away.
seopher
Written Nov. 20, 2007 / Report /
/slaps Oli
OOP in PHP isn't perfect but it is desirable. Any big project should be written in a loose object oriented way (as described above).
Basically using classes you can make new instances of objects, a common example would be using functions to return you a customer array...
$rawr = new whateverMyClassIsCalled();$customer = $rawr->getCustomer($customerID);
So there you have the $rawr instance instantiates a new 'whateverMyClassIsCalled' class.
An example of how I'd use that is seen on the second line - say I've got a customer ID in the $customerID field. I can then simply define the new variable ($customer) as the returned value from the getCustomer() method I defined within the class.
So in the class somewhere I'm likely to have something like
function getCustomer($id){
$sql = "select field1, field2, field3 from customer where id = $id";
$result = mysql_query($sql);
return mysql_fetch_assoc($result);
}
That should return you the associative array into your $customer variable.
I apologise if that's incorrect or a bit dodgy in places, i've just taken that off the top of my head.
tilespace
Written Nov. 20, 2007 / Report /
This is a great post. I've been programming for almost 15 years now and have *never* understood OOP (and yet I can program in Delphi and Pascal and similar, explain that one to me?). These are definitely the best explanations I've ever come across...
One question tho...
@anadgouda - for clarification, has Drupal changed in the past year? I spent 2 years working heavily with Drupal (expotv.com, lime.com, and so on) and I don't remember it being OOP-based. It was purely functional/procedural. I could be wrong (happens a lot) and it could've been using classes and for whatever reason I just thought they were functions (not sure how I coulda missed it tho) but maybe it's just within the past year that they've changed their framework (I became anti-opensource a year ago for various reasons)? I'm just curious as to whether I just bypassed their whole class structure or if something's new with them...
outernal
Written Nov. 21, 2007 / Report /
{function}=BOOM+{-head-}
dreamweaver
Written Nov. 21, 2007 / Report /
That works, but I thought surely there would be an emoticon (that a non-programmer would understand) for "head explosion" since it seems like there's one for just about everything else!
dreamweaver
Written Nov. 21, 2007 / Report /
Okay, I'm now feeling pretty cool about OOP, since I just figured it out, and said "Ooooohhhh! I GET IT NOW!" And it's just like I thought it would be: when I came across something in my own work where it seemed like OOP would make it easier, or cut down on the code, I was able to wrap my head around it all.
So, despite the fact that all you "seasoned programmers" may all think I've gone off the deep end and used OOP for something totally meaningless that could have very well been done some other (easier) way (and if that's the case, feel free to tell me, I'm all ears!), here's what I did:
I have to make forms (lots and lots of forms) that use many drop down select boxes, check boxes and radio inputs so that users can register for workshops online for a client. In the past, I've created the HTML for these types of inputs with PHP by iterating over an array of the options, which means I have these chunks of code that I use over and over again, sometimes many times on one page, to create all of the choices. When i edit forms to put in new workshops, it's a total pain to dig through the code, and it's easy to make a mistake that makes the whole thing give me parse errors.
I decided to define a class that accepts attributes for the array variable, the output variable "name" (in the HTML), the type of input (select, radio, checkbox), and how many choices (optional) for each option (like a workshop where the user needs to make three choices in case the first one is full). The class has a method that creates the HTML to display the input, depending on what type of input is indicated by the attributes of the class.
So now, instead of a bunch of repetitive code inside my document, I have three simple lines:
$friam = array('Basketweaving', 'Fishing');$select = new choices($friam, 'fridayam', 'select', 2);
$select->make_input();
Love it! Way easier to edit, and much cleaner. All's right with the world now. :)
tilespace
Written Nov. 21, 2007 / Report /
Nicely done!
anadgouda
Written Nov. 26, 2007 / Report /
@tilespace, Drupal is done using procedural language, but its design is inspired by OOP techniques. This is where I feel that it is a way of thinking more than the syntax and OOP jargon.
tilespace
Written Nov. 26, 2007 / Report /
ahhhh... ok yeah, that makes sense... so i'm not insane :) hm. maybe i know more about OO than i give myself credit for then... *slightly befuddled now*
tehriddler
Written Feb. 7, 2008 / Report /
Killer PHP OOP Tutorials
@Dreamweaver
This is the site finally clarified OOP with PHP for me. I too, like you, have had numerous troubles understanding what OOP is. If you watch all of this guy's video tutorials, and go though his PDF tutorial, I believe you should have all the knowledge you need to get into OOP.
Hope it helps!