[PHP] OOP PHP? Is it really worth it?

Experienced Elementalist
Joined
Jul 4, 2004
Messages
211
Reaction score
0
I have been looking into this a bit, and wanted to ask a question about it... Is coding PHP in OOP worth it? For instance, I am not seeing how:

PHP:
<?php
// The following class is in Something.php
class Something {

    function add($a,$b) {
        return $a+$b;
    }
}

// Now in index.php
include("Something.php");
$add = new Something;
echo $add->add(1,5);
?>

is any better than doing:

PHP:
<?php
// The following function is in Something.php
function add($a,$b) {
    return $a+$b;
}
// The following is in index.php
include("Something.php");
echo $add($a,$b);

Now, I have heard the advantage comes with not having to repeat, however, if you just make files containing the needed functions with correct arguments and such you are not / should not be repeating much if any unneeded code. So I am wondering, is it worth it to have to do class and all that? I keep hearing it is, yet I see no real advantage to doing it (Benchmarks show it to be slower, from what I can tell) compared to what I am doing currently (Making files filled with functions and just including them).
 
I personally dont see the benefit of doing it in smaller projects myself, I do the functions like you are saying.

I think it can be worth it, especially when there is a need for it. (larger projects for example or as griffinheart mentioned abstraction/design)

To me knowing how to use something is also as important as knowing when. (overkill = bad)

So if you dont totally understand what the OOP is doing, as suggested that is not a bad place to start.
 
It comes in handy with really large projects, where you can use the class several times with its own variables...keeps them seperated. But You shouldn't over do it, its just for structural design and some usefullness in certain situations. Often its easier to just use functions...

But overkill = bad as Madison mentioned. Sometimes I see ppl making class for everything they can, thats terribly wrong. I think if you were writing an CMS, you would need around 5 classes, or maybe less... I just use 1 (will be 2) in my gallery code you can view in my signature. Could do it without, its a class for directories, but it keeps variables seperated and looks better.
 
It comes in handy with really large projects, where you can use the class several times with its own variables...keeps them seperated. But You shouldn't over do it, its just for structural design and some usefullness in certain situations. Often its easier to just use functions...

But overkill = bad as Madison mentioned. Sometimes I see ppl making class for everything they can, thats terribly wrong. I think if you were writing an CMS, you would need around 5 classes, or maybe less... I just use 1 (will be 2) in my gallery code you can view in my signature. Could do it without, its a class for directories, but it keeps variables seperated and looks better.

Well, currently I am working on a PHP browser game and considering switching to OOP before I get *too* far into it. However, I am wondering what the benefits of making classes rather than files are.

After looking into abstraction a bit more (Still dont fully understand what Abstraction is about), I really dont see how abstraction would help me (Perhaps some one can make this a bit more clear on what Abstraction would do for me in PHP?).

Also after looking into structural design / structured programming, and I dont see how I am not doing that already? Based on how it has been explained to me, its basically keeping the functions in a class relevant to what they do, for instance class Account may have a ChangePassword() function, however I dont see how thats any better than making a file called Account.php and sticking ChangePassword() and other relevant functions into it.

So unless I am missing / not understanding a big concept in OOP, the only ability over what I am doing now is the ability to do:
PHP:
<?php
class Account {
    var $Username; // <- the ability to use vars in this sense.
    
    function getUsername() {
        return $this->Username;
    }
    
    function setUsername($UName) { 
        $this->Username = $UName;
    }
}

So am I missing a fairly large concept to this?


And yes, I know quite a few PHP coders, but they are all biased on this subject. They either code 100% OOP, or they do it like I do, so no one I know is really being of much help to me at the moment (Hence why I posted here :) ).

Thanks for the replies so far.
 
ok, oop is better then anything you just need to work it out if its worth the trouble or not, that why in small projects the effort and time you consume won't pay out.

abstraction, well you allready use it, functions are a form of abstraction,

basicly its seperating the how to use and how it works.
when you do a function after you do it you won't have to bother how it works you just have to know how to use it.

anyways let me try an example, might help, since your doing a browser game:

in a game you have users, every player is a user,
so you have a user class, wich will be your top lvl class.
In the user class you'll declare what a user is made of (variables), for example, name, dob, email, anything.
And the user class will be able to do things like changing name, changing email adress these are called methods (change_email(), change_name())

Now you can have diferent types of users admins, players, donators etc, these will be sub classes of the class user. All subclasses of the class user will inherit the traits of the upper level classes.

but admins will have methods (and variables) of their own (ban(), kill()), and players other methods
these methods won't be shared by the other subclasses of the, lets call it father, father class.

each particular object of a class is called an instance btw, so if you have general morgan has a admin he will be a instance of the admin subclass that inherits all traits (methods, variables and such) from the user class

if you still don't get what this kind of programming implicates, well if you do it by hand you'd have to for each person you'd want to add has a player, has a admin, has a donator, etc, you would have to make those variables, functions etc etc etc.

With OOP you encapsulate all the information, modulate & protect the way you build your program and the beauty of this is after you have done it, you won't have to bother with it ever again.

Now imagine suddently after 100k users registered you needed to add another variable or to add another function to the XPTO faction of your game, you'd just have to go to the code of that class/subclass and add the method/variable and automaticly all instances of those classes would inherit those traits.

hmmm....dunno if i explained it in a easy to understand way, if not try wikipedia really it as very good examples there.

EDIT: i just remmebered to point out that abstraction is one of the most important things when programming, it will make your programming life a lot and i really mean a lot easyer,

it will allow you not to have to write the same things over and over, since trought abstraction you will be able to reutilize fuctions and etc you use, to make it more easy to understand, if u have a basic OOP structure of users you'll be able to use it for every web brower game you do, you abstracted your code from the subject this will increase portability on the other hand if you do a in depth user structure you will decrease portability.

the whole point of OOP is abstraction/modularity, that is what it was created for, that is what it is used for and that what it is good for.

so try to separate the line from what is common to all things and what is a specific detail or you would end up with a structure that goes to the point of having subclasses for users that like dolls, for users that like to go around the house naked and etc...

if its just a case or 2 it not worth structuring it. i hope you get my point cause its 4am here xD i'm going to bed (sorry for typos)
 
I have to agree with Griffin, though he brings it a bit odd :icon6:

Over the years I've started to work more and more OOP, and with that the quality of my code has improofed a lot. I used to have functions with a dozen arguments and complicated return array values, these days I generally let them return a boolean on succes and give them no arguments at all since they're all members of classes which collect all the data they need.

Moreso most of my code these days I can reuse easily because it's very abstract - almost all aspects of a site don't change that much. You'll allways need a pagehandler, database connector, error handler, content retrievel system, userhandler, etc. So why use rare functions specific for your one site when you can write classes that you can simply copy & paste? :wink:

Perhaps usefull to read trough is my code here, I've worked on that tonight and it's almost entirely OOP and more importantly has an absolute strict seperation of output logic and business logic. Noteworthy are the 2 database extensions for 1 database class - they allow users to use 2 seperate datbases next to eachother which is usefull with WoW servers since they have a realm and mangos database.
 
Hmm, interresting. ATM I return complicated returns (arrays with lot of values), aha, than OOP would make sense indeed. I think I implemented OOP wrong, thats why I thought it would have no usefullness. I will look at your code :).

What is actually the definition of abstract code? That you can easily modificate it by change a few parameters?
 
I have to agree with Griffin, though he brings it a bit odd :icon6:

Over the years I've started to work more and more OOP, and with that the quality of my code has improofed a lot. I used to have functions with a dozen arguments and complicated return array values, these days I generally let them return a boolean on succes and give them no arguments at all since they're all members of classes which collect all the data they need.

Moreso most of my code these days I can reuse easily because it's very abstract - almost all aspects of a site don't change that much. You'll allways need a pagehandler, database connector, error handler, content retrievel system, userhandler, etc. So why use rare functions specific for your one site when you can write classes that you can simply copy & paste? :wink:

Perhaps usefull to read trough is my code here, I've worked on that tonight and it's almost entirely OOP and more importantly has an absolute strict seperation of output logic and business logic. Noteworthy are the 2 database extensions for 1 database class - they allow users to use 2 seperate datbases next to eachother which is usefull with WoW servers since they have a realm and mangos database.

Ah, thanks :) That tells quite a bit.


Thanks to GriffinHeart as well, that was also helpful :)


Also, FragFrog, I sent you a PM.

edit:
Hmm, interresting. ATM I return complicated returns (arrays with lot of values), aha, than OOP would make sense indeed. I think I implemented OOP wrong, thats why I thought it would have no usefullness. I will look at your code :).

What is actually the definition of abstract code? That you can easily modificate it by change a few parameters?

Had to look it up. According to wikipedia:

Wikipedia said:
abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time.

Found: Abstraction (Computer Science)
 
whoa, did I just read about returning functions with an array of data... wow.

Please don't do stuff like that. The next person (always think your code will be read by another person in the future) is going to have to figure out what the @#$%#$% you were doing when you wrote that. :P


I just want to say these few things about coding practices in general:

If you have to pass in a lot of arguements to a function, there is a better way to do it.

If you feel the need to return more than one value from a function there is a better way to do it.

If your condition statements feel like paragraphs there is a better way to do it.

Sometimes more lines of code is better than fewer (harder to understand) lines.

If you need to write a paragraph of comments for someone to understand your logic, your logic probably has issues. (comments are good but should be relatively short imo, and if you have to explain some complicated way you did something, there is probably a less complicated way to do it :P)

There is a huge difference between writing code that works and writing good code.

The most important thing you can do to code well is know your control structures (yes classes, loops, functions etc is all some type of control structure) and know them well, what they do, when, why, etc.

Coding elegance will never be achieved through brute force (and yes returning an array of data is brute force coding :P)

I mean basically, OOP is great and has its place, and FragFrog and GriffinHeart are right on with their statements. But even OOP can go horribly wrong if you aren't using it right, same as any control structure.

I suggest you write some classes for the sake of writing them, get a feel and understanding for what they do and what they are supposed to do for you. Do this before trying to apply it to something bigger.

Really the only other programming concept that is harder to grasp (for most people) than the idea of abstractions is pointers, so I honestly don't think you will pick up all you need to know from one thread on a forum but they point you in the right way and give some great examples.


Anyway that's my opinion on code and so on, blahblah

~Madison ZCE, MCAD, BS:CS BS:MIS
 
I knew returning arrays with loads of variables wasn't perfect, but now I see when OOP can be handy ;).

To be honest, I understand pointers, but I dont understand OOP very well, lol. Just like error handling lol,havent seen any advantages on that.

Anyways, I have 'If''s that feel like paragraphs :S. Thats basically because I have several scripts with the same environment (for instance admin area) in one single php file... what is the better way to do this?
 
I think you misunderstood what I meant by Condition statement.

If (condition statement) {
blahblah;
}
else if (next condition statement) {
blahblah2;
}

THOSE shouldn't be paragraphs, if they get really long its harder to understand and decipher what the point is. (although there are exceptions, just like there are reasons you would want to return an array from a function, but you don't want to throw these kinds of things around- just because its possible doesn't mean its best)

I think you are saying you have a lot of "else if" clauses...

Ask yourself... Does it have to be on one page? I mean sometimes that is more convienient but if you get a page that's 5k+ lines, it might be harder to read. (so does having it all on one page make it harder to read?) That's mostly personal preference perhaps. Especially when doing php on the web (my experience mostly) I prefer just to make a new page in many cases.



No advantages on error handling...... ummm omg.. aren't you the perfect victim for sql injection :P (seriously look up sql injection now, as you are scaring me if you are doing any work with databases and no error handling.)

Anytime you have data input by the user, I promise they don't enter what you want. You can't expect or think they will without some kind of error handling
Also: What if something simple like your database connect returns poorly or something? How would you know? How would you let the end user know?
Error handling is very important for many many reasons, even if it is just very simple.

Start out by doing things just for the sake of doing them and end up by doing things because you know from experience which is the best way to do it.

Coding is an artform, like poetry. Its more than just a bunch of words/syntax on a page.

ok i'll get off my soap box now :P
 
I think you misunderstood what I meant by Condition statement.

If (condition statement) {
blahblah;
}
else if (next condition statement) {
blahblah2;
}

THOSE shouldn't be paragraphs, if they get really long its harder to understand and decipher what the point is. (although there are exceptions, just like there are reasons you would want to return an array from a function, but you don't want to throw these kinds of things around- just because its possible doesn't mean its best)

I think you are saying you have a lot of "else if" clauses...

Ask yourself... Does it have to be on one page? I mean sometimes that is more convienient but if you get a page that's 5k+ lines, it might be harder to read. (so does having it all on one page make it harder to read?) That's mostly personal preference perhaps. Especially when doing php on the web (my experience mostly) I prefer just to make a new page in many cases.



No advantages on error handling...... ummm omg.. aren't you the perfect victim for sql injection :P (seriously look up sql injection now, as you are scaring me if you are doing any work with databases and no error handling.)

Anytime you have data input by the user, I promise they don't enter what you want. You can't expect or think they will without some kind of error handling
Also: What if something simple like your database connect returns poorly or something? How would you know? How would you let the end user know?
Error handling is very important for many many reasons, even if it is just very simple.

Start out by doing things just for the sake of doing them and end up by doing things because you know from experience which is the best way to do it.

Coding is an artform, like poetry. Its more than just a bunch of words/syntax on a page.

ok i'll get off my soap box now :P

I agree, I use error handling for that purpose, plus I find its more secure and better looking (The user dosnt need to know what line in what file in what directory the error was in, I / the other devs do).

Also, I added you to MSN (Hope you dont mind).
 
Hmm, interresting. ATM I return complicated returns (arrays with lot of values), aha, than OOP would make sense indeed. I think I implemented OOP wrong, thats why I thought it would have no usefullness. I will look at your code :).

What is actually the definition of abstract code? That you can easily modificate it by change a few parameters?


as i said abstraction in a easy way to understand are functions

when you do a fuction every time you want to use it you use the name of the function and not the code in it, if you didn't use that kind of abstraction every time you wanted to use that you'd have to put the entire code so you abstract your code to a name, from that moment you need not to care how it works, the only concern you have is "am i parsing the right data types?".

anyways theres a lot more to OOP then what i said, that was just an example if you are interested take for example the "+" operator on php.

its a polymorphic function acheavable by OOP that regardless of what data type you trow at it, it will work (sort off), and you have also compostion and agregation and a lot other goodies in OOP.

to Madison:
i really can't think of a reason for why people have hard time understanding pointers :\, but the fact is they do, damn it, a pointer is literally something that points to another thing thats all, not a hard concept to understand lol.



take this stupid example (just imagine this in your head):
you are seller of house furniture and theres 3 houses, to know wich house furniture you going to sell next you have a board on that board is the adress of that house,

note that the board here is the pointer, but the pointer doesn't "point" to the furniture (content of the house) it points to the house (container of the furniture) it self

so in programming a pointer is a "variable" that stores not the content of another variable but the adress of the variable you need.

that why in c if you try to read a pointer you get a memory adress, but if you read what the pointer is pointing at you get the content wich generally is what you want.

omg this is all off topic.


i agree with madison, coding isn't just grabbing your compiler and writing code.
fk it from my experience about 20% of your time in a project, if that much, is spent coding.
even debugging takes up more % of the time in a project.
this shows something, to everyone that eagers to be in this area, and its that coding is a small, if not the smallest, part of a project.
 
I think you misunderstood what I meant by Condition statement.

If (condition statement) {
blahblah;
}
else if (next condition statement) {
blahblah2;
}

THOSE shouldn't be paragraphs, if they get really long its harder to understand and decipher what the point is. (although there are exceptions, just like there are reasons you would want to return an array from a function, but you don't want to throw these kinds of things around- just because its possible doesn't mean its best)

I think you are saying you have a lot of "else if" clauses...

Ask yourself... Does it have to be on one page? I mean sometimes that is more convienient but if you get a page that's 5k+ lines, it might be harder to read. (so does having it all on one page make it harder to read?) That's mostly personal preference perhaps. Especially when doing php on the web (my experience mostly) I prefer just to make a new page in many cases.



No advantages on error handling...... ummm omg.. aren't you the perfect victim for sql injection :P (seriously look up sql injection now, as you are scaring me if you are doing any work with databases and no error handling.)

Anytime you have data input by the user, I promise they don't enter what you want. You can't expect or think they will without some kind of error handling
Also: What if something simple like your database connect returns poorly or something? How would you know? How would you let the end user know?
Error handling is very important for many many reasons, even if it is just very simple.

Start out by doing things just for the sake of doing them and end up by doing things because you know from experience which is the best way to do it.

Coding is an artform, like poetry. Its more than just a bunch of words/syntax on a page.

ok i'll get off my soap box now :P

Sorry, I wasn't very clear. I actually _do_ handle errors, just what you said: lot of things can happen. But I actually meant the exception/error catching build-in function of php, which has no usefullness IMO because I have my own error handling. Im not a total idiot ^^, hehe ;)

About the condition thingy. I have a small admin page, 1k lines, with like 8 if's or elseif's filling the page. Some are 10 lines long, but some can get little long. So I was wondering what a better method would be. But its not dramatically long...
In general, putting pages with the same subject in one page makes it easier to edit. Than you dont have like 10 pages for admin etc. But well, personal preference indeed ;)

Anyways, Im structuring my code. I took a look at FragFrogs download link. I managed the files just like that, now going to write the classes, the good way :P. Thanks.
 
Griffin: well duh, PHP pointers are easy. But it took me a while too to understand and comprehend C++'s pointers and references to be honest :icon6:

Daevius: while you're at it, have a look at the new ZEND framework too! Haven't had a chance to do so myself but I'm hearing excelent reports on it :icon6:
 
I'll definitive recomend the Zend Framework. Their ORM is so sweet, and helps you avoiding having to do CRUD all the time when working with data collections.
PHP don't got pointers, but you're able to pass stuff along as refferences, which is the most common use of pointers in C (due to the lack of typesafe custom types).

As many said, OOP is a way of designing your code. It's not to produce different code, it's about the readability and the structure. It's so 5000 people on the same project easier can find, read and documentate the different parts of your code.

If you're interested in samples, and otherwise different crazy php stuff, check my repository: dragons-lair.org | Repository
 
I'll definitive recomend the Zend Framework. Their ORM is so sweet, and helps you avoiding having to do CRUD all the time when working with data collections.
PHP don't got pointers, but you're able to pass stuff along as refferences, which is the most common use of pointers in C (due to the lack of typesafe custom types).

As many said, OOP is a way of designing your code. It's not to produce different code, it's about the readability and the structure. It's so 5000 people on the same project easier can find, read and documentate the different parts of your code.

If you're interested in samples, and otherwise different crazy php stuff, check my repository: dragons-lair.org | Repository

Aye, your code looks nice, been looking at it for a bit now. I think I am going to look into the Zend Framework a bit also.

Though, I do not expect many people working on this with me (I am not going to make it open source or release it, at most I will have a few other developers helping with creating patches after I make the game), however I cant stand sloppy / poor code so I keep it as clean and such as possible and I expect anyone who codes projects with me to do the same (If they dont, I wont use the code, id rather make it myself).
 
Aye, your code looks nice, been looking at it for a bit now. I think I am going to look into the Zend Framework a bit also.

Though, I do not expect many people working on this with me (I am not going to make it open source or release it, at most I will have a few other developers helping with creating patches after I make the game), however I cant stand sloppy / poor code so I keep it as clean and such as possible and I expect anyone who codes projects with me to do the same (If they dont, I wont use the code, id rather make it myself).

Indeed, code looks good.

I took a quick look at the zend framework. Looks good and usefull :), but it always takes ages for me to find out all functions and use them. Thats why I often write it myself and modify it to the project's needs, that way I learn the most but the code won't be as optimized as professional code like the Zend Framework.

Even if its not open-source its good to keep it organised ;). Because after a few months you probably forgot what some functions/pieces are about :P.
 
Back