OOP vs Procedural PHP

Which is better?


  • Total voters
    14

lambada

New Member
Messages
2,444
Reaction score
0
Points
0
HI all,

I'm looking to switch from the procedural PHP to Object Orientated PHP, but I'm at a loss as to any good tutorials on the basics. I've tried the PHP manual - but its foo bar code samples aren't exactly the clearest.

BTW:

OOP is the classes, whereas Procedural is what most tutorials are in.

Also, I'm interested to know which you think is better and why (i've heard most of the pro-OOP argumentss code reuse etc), but not many pro Procedural ones.

So if you can tell me how you made the switch i'd appreciate it.

Also if I make the switch expect many more threads needing help ;)

lambada
 

Anna

I am just me
Staff member
Messages
11,244
Reaction score
523
Points
113
I'm not a php coder, nor familiarly enough with it to try, but I've done some c and c++ coding, and the same things as to weather to use procedural or OOP applies to php as well I think.

For smaller things procedural would probably be easier and possibly faster to handle, but when you write larger apps OOP is the way to go, for code reuse and such things you already heard.

OOP makes it a lot easier to maintain and modify apps without rewriting a large portion of code. As long as the parameters you can put into a function remains the same you can do what ever changes you like to what is done with them. The part of code that calls the function doesn't really care what you do as long as the return value is in an expected form.

can't really say I heard anyone give pro procedural advice other then when it comes to small tasks.
 

deadimp

New Member
Messages
249
Reaction score
0
Points
0
I think LadyAnna pretty much said it. I use OOP because the organizational benifit far outweighs any sort of 'convenience' that all-out procedural can offer. Now saying that, I'm not an OOP-nazi. I program mainly in C++, not Java, so I do switch between global functions/variables and class-scoped functions/variables (or members/methods). In all honesty, I'm a hobbyist programmer, and I've never really taken any formal classes (except for High School Computer Science, which is a friggin' joke), so my advice isn't part of the 'industrial standard'.
If you just want some examples of OOP to browse around, you're likely to find them in projects using an MVC architecture, such as CakePHP (which deals with more than PHP, though). Other things you might want to look at are the Zend Framework, or CodeIgniter, or maybe some of the big CMSes, like Joomla or Drupal (can't say if they stuck with procedural or OOP most of the time).
Heck, I'll put my usual plug in. You can browse around the source for Thacmus, my CMS project. I've designed with things I've learned from programming namely in C++, which also consists of stuff I learned (to love and hate) with GML, VisualBasic, JavaScript, etc.

My story: [Kinda long...]
I started learning PHP a while ago, after I had been using Game Maker (thusly GML), meaning I had no experience with OOP whatsoever. I was procedural all the way, and scoffed at people who had to use classes to organize their code. After half a year of just screwing around with PHP, not really doing much, I left it and went back to mainly using GML. I later got tired of GML, and finally decided to learn C++ (for the third time). That time, after experience with GML and PHP, I could grasp the syntax of C++ a little more easily. I started to program crap, and then decided to start writing a game with C++, and for that matter, a game engine, just for learning experience.
I started out trying to make it as close to GML as possible, meaning I used classes sparsely, and only then for polymorphism and grouped variables. I hardly used normal functions.
After a while, I realized why I had stopped using GM, and stopped trying to imitate it, and went off on my own designing things how I liked.
It gradually evolved, and I frequently tore it apart, refactored it, redesigned, left it for a couple of months or so, came back, did the same thing, and so on, just so I could get around to working on a MegaMan X fan game I wanted to do. Needless to say, I have quite a bit of A.D.D. (normal for a programmer), and switched back to PHP for a while, since I was helping out with my school band's website.
When I began to compare the way I coded with PHP before and the way I coded with C++, I realized that using OOP with PHP is actually a good thing to do. I noticed this when I was designing the framework for the band's site, and I noticed how repetitive certain tasks were. I also remembered how much of a pain in the ass it was to write MySQL code with PHP (I had written some bus signup software just for the hell of it, and it was truly a pain), so I thought to myself, "What's the best way?" So I programmed some stuff in procedural like I used to, looked for patterns, started simplifying the patterns, encapsulating the patterns, generalizing them, abstracting them, yadda yadda yadda.

Yeah, I was kinda windy there, but you get the point.

EDIT: Way too windy.
 
Last edited:

DefecTalisman

Community Advocate
Community Support
Messages
4,148
Reaction score
5
Points
38
Uhm... slap me and call me daft.

Whats the difference?
is it just the way the program is written.

eg: instead of constantly writting a routin you would create a sub/function and "requier" it with the vars. everytime. Thus cutting work/size down.

? ? ?
Edit:
eg: error log

print "$test01\n" or error("place where error ocured", !);
print "$test02\n" or error("place where error ocured", !);

error {
($tmp, $er) = $_;
print "$tmp"."$er";
}

instead of

print "$test01\n" or print "place where error ocured".!."\n";
print "$test02\n" or print "place where error ocured".!."\n";


This example is not functional, it is perl/php(for perl write sub, for php write function)
Edit:
I know this might sound stupid and am going to test when I finish work.
But if anyone can save me the time.

Can I write a CSI with php and have it requier a perl include?
eg:

<?php
requier "test.pl";
(what ever subroutine or function here)(vars to pass to the sub/function);
$returned_vars = $_;
?>
 
Last edited:

halohalo

New Member
Messages
54
Reaction score
0
Points
0
I too have made ajump into OOP with PHP. The latest book I'm reading is a guide on PEAR (the PHP Application Extension and Application Repository) and the more I read, the more I like having a framework of libraries of pre-written packages to simplify my PHP coding efforts. I mean, it maybe a useful exercise, but writing PHP from scratch and reinventing the wheel every single time seems a bit pointless. Check out the PEAR documentation of the available packages and you'll see what I mean.

Check out PEAR if you want a sample of what OOP can do. The x10Hosting developer package supports PEAR which is awesome! Go OOP!
 

deadimp

New Member
Messages
249
Reaction score
0
Points
0
Whats the difference?
is it just the way the program is written.
Yes, that's the entire difference. You use almost any method to program someting, but which way has the most ease? Which way cuts down the most repetition, while remaining functional and understandable? Which way makes the code easily modifiable and flexible?

Also, what were those examples of?
 

DefecTalisman

Community Advocate
Community Support
Messages
4,148
Reaction score
5
Points
38
Also, what were those examples of?

A short handed version of a error log/system.
Instead of saying
"do this or die with this message"
"do this or send these vars to something"

so object orientated would use subs/functions that are uniform?

another (maybe better) example:

everytime a user clicks a link, a check on the users system and browser is done.

So rather than writting this out at that point in the program you could send it of to a include and let it return witht the result.

? ? ?
 

deadimp

New Member
Messages
249
Reaction score
0
Points
0
The examples you're giving don't exactly entail an OOP approach. I'm not sure I can explain things all too well, but if you want to see differences in coding for a library between OOP and procedural, check out the code examples in mysqli.
Now, these don't go too deep into the aspect of OOP, but give a brief view of some of the differences.
 

DefecTalisman

Community Advocate
Community Support
Messages
4,148
Reaction score
5
Points
38
ok, that link just made me read about MySQLi and i bearly know MySQL.
Still dont see any examples...
 

mitamata

New Member
Messages
81
Reaction score
0
Points
0
Object oriented php isn't just functions. It's functions in an object (an instance of a class), hence the name. For the example you used, you could make an error class and use that. Something like this:

class errorObject
{
public $tmp;
public $er;
public $errorLogged;

function __errorObject ($tmp, $er) //this is the object constructor, works with php 5
{
$this->tmp = $tmp;
$this->er = $er;
}

public function writeError ()
{
$this->logError();
print ($tmp);
print($er);
}

private function logError ()
{
//some code that logs the error to a special file or database
//when logging successful, do the following:
$this->errorLogged = true;
}
}

You'd use it like this:

$myError = new errorObject ($someVar, $anotherVar);
$myError->writeError();
if ($myError->errorLogged)
print("Error was logged to file.");

You could of course have the class constructor call the 'writeError' function and print the last line, which would cut down the code to only the first line - just create the object and that's it. But if you eventually wanted to do more with the object, it's better to do it like I did.
The example is not very useful, it's only ment to illustrate what a php object is. But maybe you can imagine how the same principles could be useful in much larger objects.

Here's an example of how an object could be useful:

$myPerson = new Person($personID, dbConnection); //create the object
print($myPerson->personName); //print a variable from the object
$myPerson->changeLastName($newLastName); //call a function of the object
print($myPerson->personPet->petName); //print a variable from an object inside the 'Person' object

'Person' is an object that takes an ID of a record in the database and retrieves the data about that person from the database, storing it in object variables. One of its object variables is a variable of a type 'Pet', which is also an object and contains the information about the person's pet, which it also retrieves from the database (an object named 'personPet' is created in the constructor of 'Person'). I've written only 4 lines of code, but there's many more lines in the objects. But just looking at those 4 lines, you can tell what the variables/functions are, no? My personal favourites here are the object variables. I don't know how I ever programmed without them. lol

I switched to object oriented PHP a few months back when our company got a big project we decided to do in php. It has a LOT of code, there's several programmers working on it and I don't know if we could handle it without objects. When I first started writing the code, I really didn't like it. That stems from my dislike of objects in c++ (our teacher at school wasn't much, I never figured out why objects were useful). It felt like it was just more work. But as the lines of code multiplied, I noticed that it actually is better, my php code was far more readable, more organized and much shorter. And the more you use it, the more good things you discover about it. It just grows on you ;)
And it's easy to learn, all you have to know are some object basics.

Honestly, I can't see what the pros for procedural php would be.

If you decide to use classes, have a look at http://www.phpclasses.org/ (you'll probably have to register to see most of the classes). There's a lot of useful classes on there. I've used a few, they saved me quite some programming time :)
Yet another useful thing about classes: you can grab them off the internet ;)


Heh. Long, but hopefully also useful.
 

DefecTalisman

Community Advocate
Community Support
Messages
4,148
Reaction score
5
Points
38
I think i have made the transition.

Just made a Image include.
So far the functions in it are:
resizeImage:
first parm passed is the image location.
parms that can be given for size are: width,height,%,both,default.
other parms: map, href, alt.
PHP:
$image = location ,
$alt = tag,
 $map = picmap name,
 $x_y = either 'width','height','both','%',
 $std_resize = '100' or '100x100'
resizeCoords.
PHP:
$shape = area shape,
 $x_s,$y_s,$x_e,$y_e = coords,
 $map_text = desc,
 $map_href = http://,
 $map_targ = open how,
 $map_alt = tag

would this count as OOP?
Edit:
and after reading Mitimata's last post I can answer my own question and say no its not.

Bugger.
 
Last edited:

programmer

New Member
Messages
1
Reaction score
0
Points
0
i prefer OOP because it give the organizational ability especially when the applications become larger
 

DefecTalisman

Community Advocate
Community Support
Messages
4,148
Reaction score
5
Points
38
I just went from OOP to precedual in a script that I just made. Started getting to much to concentrate on !

Maybe when its finished I will take it back to OOP.
 
Top