Classes. What's the point? - php

I'm fairly new to OOP in PHP, I've made a couple of basic scripts but nothing impressive. All I've really taken from it is that it would probably be easier just make a collection of functions and include them.
The structure of classes seems to just confuse what was otherwise a simple process. And in collating everything into a class it doesn't really add any functionality.
So I'm clearly missing something. Could someone explain what functionality is added by creating classes

Classes are a notion of object-oriented design (and programming and analysis, respectively), where they are used to encapsulate data and methods.
Other object-oriented programming techniques may include features such as
information hiding,
data abstraction,
encapsulation,
modularity,
polymorphism and
inheritance
From an article .. top-15-best-practices-for-writing-super-readable-code:
Object oriented programming can help you create well structured code. But that does not mean you need to abandon procedural programming completely. Actually creating a mix of both styles can be good.
From http://java.sun.com/docs/books/tutorial/java/concepts/class.html:
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
Finally, a short youtube video about the differences between the procedural and object-oriented programming paradigm ...

While it may at first look simpler to just use a set of functions and include them, classes have their strong points. Classes can store variables and those variables are there "later."
Here's an edited example from php.net
<?php
$item_name = 'Widget 22';
$item_price = 4.90;
$item_qty = 2;
$item_total = ($item_price * $item_qty);
echo "You ordered $item_qty $item_name # \$$item_price for a total of: \$$item_total.";
?>
v.s:
<?php
class Item {
protected $name, $price, $qty, $total;
function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
function calculate($qty) {
$this->total = number_format(($this->price * $qty), 2);
}
public function __toString() {
return "You ordered ($this->qty) '$this->name'" . ($this->qty == 1 ? "" : "s") .
" at \$$this->price, for a total of: \$$this->total.";
}
}
$widget22 = new Item("Widget 22", 4.90);
$widget22->calculate(2);
echo $widget22;
?>
Another huge benefit is that you can make more of them. Say you want to calculate the price of another item and print it. Instead of having to duplicate all the fancy logic, you can just call new Item and be done.

A big advantage to OOP is code reuse. An example: Say you design a generic "Socket" class, which communicates with a server at a very low level. Then, I may come along and decide that I want to write an FTP class, which allows a user to download files while connected to an FTP server. I can "subclass" your Socket class and extend its functionality to support FTP, without rewriting your code.
Now, say John wants to write an HTTP class, to interact with HTTP servers. He, too, can subclass your Socket class to accomplish this, without rewriting the low level socket code.
Notice how in this example there was no duplication of socket code; both me and John shared it. Code duplication is bad because if there is an error in the duplicated code, the exact same bug may occur somewhere else in your code and you may not realize it.
More detailed information about classes can be found on Wikipedia.

Classes are a way to organize programs. Classes can be used to represent entities in the real world, or artifacts in our programming world, reducing the complexity of programs by allowing us to reason about them in terms of a higher granularity.
It is well-known in psychology that experts organize knowledge into "chunks" to allow them to reason more easily and quickly about their domain. Classes allow us to reason more easily and quickly about our programs.
In addition, classes allow us to group together the knowledge about an entity together with the methods/procedures/functions/operations that are naturally associated with that entity. Again, this provides a natural way to organize the information in our programs.
There are other advantages of classes, such as inheritance, but primarily classes are a cognitive way of organizing program structure to reduce the complexity.

Just a coupl months back I was posting similar questions about classes, I have been using PHP for a few years now and I really didn't see a need to use classes, they just complicated a simple process like you said, well I finally decided to jump in on the Class train and I am still learning but I am comfortable using them now and WOW I have a completely opposite way of thinking about them now, I think they are the best feature in PHP now!
I will admit they can be overkill for a small application but a large social network site like mine is far from small, it has hundreds of files and now that I am converting over to classes it is structured much better now and easiar to build, update, manage my code and other users could come in and understand my whole site a lot better now that it uses classes. Another great feature is you can break up all those functions you might have into seperate class files and use autoload() function to auto load the correct file only when the class is needed, this is great on a big project too. Classes make things more plug in play.
All I can say is it's kind of one of those things you need to dive into to see the REAL benefits of it.

I have thought exactly the same thing.
I have read a few books on OO-PHP, my favorite being PHP In Action.
Although when I read the books I thought "Hey, this is very useful and interesting information.", I have yet to use a significant amount of OO-PHP.
Simple needs like getting info from the server and JSON-ing it back really dont need OOP. Im sure it is "Best Practice", but for many people's needs it isn't practical. A few classes, like database connection, and similar data handling can be real time savers, but PHP is sometimes easier and quicker to be used only partially OO.

It would definitely be easy to code in procedural programming (that's what your simple process is called) if your website is small. But as your website grow, you will definitely need to sort things.
For example, you will need classes to act as templates for entities to the database. You might need classes to represent each page, and in a single file you might create multiple pages. Thus these are all advantages of OOP.
In another example you have like 40 over functions. You would want to group them together. Putting them in a class as static methods would definitely help. It'll clean things up so that in future when you come back to the same code, everything looks familiar to you.

I always thought the same thing until I started using classes--realizing that it is so much simpler and better.
You should create those functions that you're mentioning, but gather them all within a class. The functions can then within a class share the same variables, and therefore making it simpler when having to use the same functions multiple times.
The best example I can come up with now is connecting to a database.
Instead of having individual functions that connect, sends a query, fetching the results and closing the connection you could wrap all these functions within a class. This would allow you to communicate to the database multiple times using the same functions, without having to make loads of variables tailored for the specific use on the page.

If you're just writing procedural-style functions then slapping them together into a class you're not going to get many of the benefits of OOP. I think that the Open Closed Principle and the Dependency Inversion Principle describe some of the biggest benefits of OOP, which you wont get unless you intentionally design them into your code.
OOP isn't perfectly suited to everything, though. I think procedural programming is well suited to web development. It involves converting a (fairly) simple request into a bunch of HTML, which is a highly procedural task. If it's simpler to include a few functions, there's no point trying to shove an OOP shaped block into a procedurally shaped hole. However, I imagine that OOP would be the better option if the website was very complex.

All of the above poster have really good points. I would highly recommend the following books:
The OO Thought Process: http://www.amazon.com/Object-Oriented-Thought-Process-3rd/dp/0672330164/ref=sr_1_5?ie=UTF8&s=books&qid=1262547120&sr=8-5
PHP5 Objects, Patterns & Practice: http://www.amazon.com/PHP-Objects-Patterns-Practice-Second/dp/1590599098/ref=sr_1_3?ie=UTF8&s=books&qid=1262546817&sr=8-3
OO Design Heuristics: http://www.amazon.com/Object-Oriented-Design-Heuristics-Arthur-Riel/dp/020163385X/ref=sr_1_1?ie=UTF8&s=books&qid=1262546869&sr=8-1

To manage complexity.
Edit: Maybe I shopuld elaborate a bit more.
Programs are complex entities and many ways have been proposed historically to tame their complexity.
Procedural programming, functions, structured programming, abstract data types and object-oriented programming are just models to help programmers manage the mental effort that is required to understand a program.
Object programming will not solve everything, and certainly for a small script it is overkill, but it works great for big applications or systems.
My original answer tries to summarize the full content of the humongous Code Complete book: do your best to manage complexity and make your programs understandable for you and your successors. It's great if you think that object programming will help you in this task, but it's even better that you question its convenience and try to find better ways.

In PHP, classes can, at the very least, save you a bunch of include statements. The lazy loading of the __autoload() function is very handy. Also, you can be confident that function names in different includes won't conflict.
To go beyond that, you can start to think of creating an API around a class. Functions which are needed only by other functions within the class can be marked private. And eventually, you should be able to ignore the actual code in your classes, and just think of them as API calls.
If I call Do::stuff($a, $b) I get this response.
And that's all you need to know. You can forget how it works "under the hood" inside the class.
And then, of course, there's classes with non-static functions. These can do various interesting things that normal functions can't.

Related

Why should I start writing object-oriented code in PHP?

I have been using regular PHP for some time now. My formal code training is zero. Whatever I've learned I've found here, on the PHP documentation site, the MySQL documentation, etc.
I write PHP from scratch. I use functions for tasks that re-occur, I apply MVC to write more maintainable code, and I recently wrote a nice little library with some of my functions so I can save time in future projects. Long story short, without being some sort of guru, I have a decent relationship with PHP, and so far it seems to get things done for me.
So my questions are the following: Why should I start writing object-oriented code in PHP? How will it make my programming life better and why is it better than the traditional way of doing things?
OOP was made to make programming languages more similar to real life.
What does that mean?
We live in a world of objects. You are an object (Person), you live in an object House, that House object (as well as any other House object) has an House::$address and House::$number, your house probably contains other objects such as LivingRoom and Kitchen. The Kitchen can hold Oven and Stove and Refrigerator, which are all extensions of the KitchenAppliance object.
OOP programming takes that approach, and incorporates it into the programming world.
How does it help me?
Well, there are several things:
It makes your code more maintainable. Instead of dividing your program into tasks (functions), you divide it into objects, if you think of a database connection as an object (meaning, there can be multiple database connections, they share methods and properties, but each is preformed on a different instance), it makes it easier to understand and maintain.
It makes your code more readable. You define an object with the class decleration, and then call it with the new ClassName() keyword.
It allows for extensibility and flexibility. Just like KitchenAppliance can be extended into Oven or Stove, so can your objects and classes.
Summary
OOP programming comes with many advantages. It requires a slightly different way of thinking, but eventually, it's worth it.
You have received a lot of comprehensive answers, so I will use one argument: design patterns. (http://en.wikipedia.org/wiki/Software_design_pattern).
You can find tones of solutions for commons problem, which can save your time and improve quality of your code.
Some design patterns examples:
Strategy pattern (http://en.wikipedia.org/wiki/Strategy_pattern) - for using different alghoritms/solutions in class without changing it
Observer pattern (http://en.wikipedia.org/wiki/Observer_pattern) - you can invoke different actions (and register them during execution) - when state of object changes.
Decorator pattern (http://en.wikipedia.org/wiki/Decorator_pattern) - you can extend your object dynamically, and use new objects in same manner as old.
Franky speaking, if you want to better understand OOP, you have to:
Learn or understand common design pattern.
Start using unit testing, you will find out that lack of dependency injection can be real pain in bad architecture.
learn and understand OOP principles, like SOLID http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29.
Without this you will be using functions encapsulated in classess, like in namespace, not OOP.
For sure you can write your code without OOP and try to implement designs/patterns like MVC without using just a single object.
I don't want to answer why to program in OOP. This you could read in e.g. on this Stack Overflow question.
I think you want to know, when and why you would fail with your coding behavior:
This would be at the moment when you try to work with another person together. The other programmer would never find your code readable. He will take a long time till he understands how your software works.
I think it's hard to separate tasks in your code for teamwork. How are your files separated, and how is the naming convention? You have to solve this by your own and don't reuse every known pattern.
What are you doing with third-party stuff? How do you integrate them? I do not know any usable library without using an OOP schema...
There are many more problems which are surely possible to solve, but every time you lose the possibility for others to understand your code and to reuse it in other programs...
One word: cohesion.
When you start developing software using objects (especially when those objects use Dependency Injection), you find that common functionality starts to gravitate into their own specialised classes that are reused. This makes maintaining and enhancing the software MUCH easier, and results in higher quality software.
Example:
Many applications use sessions, for storing all sorts of stuff. When all session data is managed by a specialised session manager class, all the code that is responsible for dealing with the session is kept in one place. If you want to change the way you application uses session data (perhaps to make it more secure, or more efficient), you only need to change code in one place.
I made the jump to OOP PHP three months ago and it is one of the best things I have done.
I started off with PHP Object-Orientated Solutions and have just finished Real-world Solutions for Developing High-quality PHP Frameworks and Applications. Both of those books have helped me a lot, and I highly recommend them.
The learning curve is quite high. But I guarantee, you will be glad you've turned to OOP.
With OO you can develop applications a lot faster and in a cleaner way. You could easy to reuse your extisting classes with extending them (reducing your code base).
With OO design you only have to deal with small pieces of codes at any one time, not a bunch a functions in a file with 3000+ lines of code. You should also look after the
SOLID guidelines.

I have been writing PHP without "classes" for years... what am I missing?

For the life of me, I can't seem to wrap my head around "classes" in PHP.
I have managed to write large, scalable, and popular websites without them.
What am I missing? (And how do I learn?)
Classes will help with code re-use and potentially a very structured application.
Procedural programming can be a lot faster in both development time and execution speed.
OO programming is the more mainstream way but not always the best way. Theres a book called PHP Objects, Patterns and Practice which is a very good read, it covers the basics of classes, why and how to use, abstraction and common design patterns such as MVC. It also covers unit testing and other very good practices for php developers
The point of classes (object oriented programming) is that it bundles data together with the code that operates on it. If done well, this leads to less tightly coupled and thus more maintainable code.
In practice it means fewer global variables (whether used directly or accessed through static factory methods) and lesss passing around of data (i.e. smaller method signatures).
For a concrete example, look at the Mysqli extension: each function has a procedural and an OOP version, and the procedural version nearly always needs to have an extra "link" parameter to give it context, wheras the OOP version gets that context from the current object.
Everybody answered was right you are missing a lot because let's say you have a photo gallery website
instead of writing functions and in the end you end with a lot of them
OOP would be useful in:
Code organization and maintainability
Adds clarity, and reduce complexity
Emphasizes data over procedures
Code modularity
Code re-usability (Believe me you will need that a lot)
Well-suited for databases
I wasn't using OOP before but i started and to be honest not very long time ago, and found it very useful in those points specially in the re-usability of the code
Let's say i have a photo gallery website
i will create a class for users and this class will do CRUD on all of the users table
and a class for the photos to do the CRUD on all of the photographs table
I could also make a class to do all the CRUD for me without specifying on what table
and then use the inheritance to extend all the CRUD in my users class and my photograph class
the point in that is i could only write the CRUD methods once
and then re-use it in all of my other classes
I hope i would have answered your question
IMO, If you do not wish to seperate your htmls & php code; you better not use classes.
You'll need them in a framework environment (not necessarily), and you'll need them if you want to objectify your datas, handle them like that.
but if you're fine without it, then you're just fine :)
When it comes to handle a very complex system, with a lot of different data structures, more than one team members, etc. You and your code need to be organized very well, and you'll need classes.
Good question! You got my upvote!
Straight to the point:
You're missing a whole world!
There are many metaphors to describe it but there's nothing better than practice - you obviously know it after "years" of programming!
Decide on a small project and write it OOP style. Then you'll get the idea.
Take this tip as well: Name your classes as their file names (ex. "MyClass" -> "MyClass.php"). Easy to maintain.
You are probably missing testability: I guess your functions call other functions, which in turn might call another function, right? So you will have trouble testing an isolated function. With OOP you assemble "heaps" of objects and can interchange each object with a "fake" one (called mock or stub) for a test. This way, you can test each functionality in isolation. Think of being able to test you output code without needing a database. Think of testing your controller code (the code which processes the request parameters and decides what action to take) without needing a web server.

When and why should I use class in php?

I want to know when and why should I use class in php, I read at php.net that a class contains variables (we write var before them) and functions for these variables, so why not use regular functions ? I mean what does class do ?
and thank you.
Often suggested advantages to using an Object Oriented Programming (i.e.: OOP aka: class based) approach instead of traditional procedural programming are that OOP aids maintainability and provides a clearer separation of concerns (in the main due to the fact that an object is effectively a set of data and the operations that related to that data), although well constructed procedural code won't necessarily be significantly worse than a OOP approach.
Irrespective, I'd be tempted to take a look at the discussion over on: simple explanation PHP OOP vs Procedural? as I suspect this will answer many of your questions.
That said, it's worth bearing in mind that there's never a "one size fits all" approach, and sometimes a mix of both procedural and OOP is ideal.
Also, if you're a beginner to PHP (or programming in general) sometimes OOP (especially large frameworks like Zend) can initially seem overwhelming, but it's often worth the effort getting to know them. (It'll pay dividends down the line.)
As a final point, I'd personally say that OOP is generally more of a "systems thinking" approach, in that large systems generally break down (reasonably) naturally into objects. From the perspective of someone who's been using OOP for too many years to mention, I'd also say that it's at the very least worthy of some serious investigation. (The Wikipedia entry is as good a place to start as any.)
Using a class allows you to encapsulate and re-use code. Here's an example (PHP 5):
class car {
public $color;
public function __construct($color) {
$this->color = $color;
}
public function show_off() {
return 'This car is ' . $this->color;
}
}
// And now I can re-use the code elegantly:
$car_one = new car('blue');
$car_two = new car('red');
$car_thr = new car('yellow');
echo $car_one->show_off(); // This car is blue
echo $car_two->show_off(); // This car is red
echo $car_thr->show_off(); // This car is yellow
I must say that, like you—when I was still very green—I felt like OOP was a solution in search of a problem. But, after diving in and using it, eventually it clicked.
Objects, in their simplest form, are like containers of logic and data that you can pass around. This can be very advantageous.
And yet, I remember my mindset when I first started learning OOP. The above example would not click. The only way to appreciate it is to use it. Once you do, you'll be very glad you did.
Classes are a convenient way to group data and functionality. You could make a class to contain person information. Then, if you want a list of persons, you can make an array and put in it an instance of the class for each person. You fill the variables of the instances with data for the persons. This looks a lot like a two dimensional array (like an array of array of persondata), but it is more. You can build functions that are contained in the class that operate on the variables in the class. You could hide functions and variables from outside, so when you're building a framework you can distinguish between internal and external functionality.
And then, there is not even spoken about inheritance, which gives you even more possibilities.
All of this can be done in procedural code as well, but OOP (for Object Oriented Programming, which is programming using classes) gives you a whole new view on structuring your code.
Many big books have been written about this subject, so it is impossible to describe the exact details and possibilities in this post. All I can tell you is that you should give it a try, keep trying a while during the initial frustrations you'll encounter. And then, when someone else asks you this question, you'll advise them the same thing. :)

Usefulness of loading instances in OO PHP?

I was asked to do a project in PHP and to make sure it was object oriented. I've done OO and I've done PHP, but never both.
The main benefit of OO PHP (outside of inheritance/polymorphism) seems to be code organization. That's fine; I'm doing that. But where I get stuck is if I should actually be creating instances for every "object."
To me (and maybe I'm being naive here), a web app is all about making very short, stateless requests to alter or retrieve records in a database. The objects can't persist between requests. So it feels rather pointless to load data from the database, construct an object from that data, make a small update, save the data from the object back to the database, and then throw the object away. The loading/saving code seems to be a lot of work for nothing. [clarification: a waste of development time, not processing time... not too concerned about overhead]
The alternative is to have a bunch of singletons (or classes with static methods) that just provide a nice, organized abstraction layer to the database layer. I guess writing code in this manner just doesn't feel truly OO. Am I missing something or is that style fine?
Yes, you could summarise the benefits of OO as "code organization"; but this is true for all languages (not just PHP). In reality, it's more than that; it's about how you think about your data structures and algorithms, i.e. about how they map to concepts in the problem domain, how they relate to one another (ownership, parent-child, polymorphism, etc.), and how they expose clean, consistent interfaces to one another (encapsulation). If these concepts would benefit your application, and outweigh the extra development time vs. a quick-and-hacky procedural solution, then go for it.
I don't think persistence has anything to do with it.
I think you should question why you've been asked "to make sure it was OO". This seems like a pretty arbitrary request without further justification. Normally, the approach should be to write your application in the style that best suits the requirements, not arbitrary whims...
Singletons are essentially just global variables with some namespace sugar added in. There are a few main benefits to programming with objects and classes that you just don't get from straight procedural programming. One is inheritance, as you mentioned. Another is the namespacing - you can have a code to compress the lot into a single include file (more meaningful in interpreted languages like PHP than in compiled languages).
Objects are essentially a collection of functions with a shared state (though singletons make that a global state. Beware.) As you pointed out the benefit is mostly that that state is transparently shared by the functions without needing to explicitly pass it every single call. If you have various functions per request operating on shared data and wish them to be specialized forms of a general set of functions, OOP is probably a good fit.
Since you have been tasked to "make sure it is object oriented", I'd take some time to consider common groups of functions, generalizations of same, etc.
In the end the setup/teardown time of the objects isn't too bad - and it might even save some development time in the future if you do a good job.
I think OOP is just a programming style and has nothing to do with developing an application. What you need is a pattern that provides a sufficient abstraction layer (for example: MVC).
My recommendation is: Fat-Free.
It's tiny, simple and quickly take you to the minimal viable version of your product. It has everything that you might need (Caching, ORM, CRUD, Captcha...) and is so flexible that you can use any pattern and with your custom directories hierarchy.
Check out the extensive documentation. The only issue is that it requires PHP 5.3. I think it's reasonable considering the options and flexibility it offers. It really changes the way you work; you should definitively give it a shot.
Like most things in life answer is somewhere in a middle.
Todays application use ORMs (for example doctrine for php) for different kind of optimization, better understanding of database approach (which is important for larger dev teams), easier update of the code, abbstraction layer that is well known to people who join the project, caching mechanisms,....
Classes with static methods are just fine if you are doing some smaller project on your own, but when more people are involved in progress you simply need something more robust and standardized.

What are the benefits of OO programming? Will it help me write better code? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm a PHPer, and am not writing object-oriented code.
What are the advantages of OO over procedural code, and where can I learn how to apply these ideas to PHP?
It doesn't help you automatically. You can write worse "OO" programs than structural programs, and vice versa. OOP is a tool which allows you to create more powerful abstractions.
As with every powerful tool, you have to use it properly.
As with every powerful tool, it takes time to learn how to use it properly.
As with every powerful tool you will make mistakes.
As with every powerful tool you will have to practice a lot.
As with every powerful tool you should read a lot about it, and read what other people think. Learn from others.
But, as with every powerful tool, there are people out there who misuse it. Learn to not learn bad practices from them. This is hard.
Objects help keep your code isolated between different sections, so that if you need to make a change to one section you can be confident it won't affect other sections: loose coupling.
Then, when you've done that for a while, you'll start finding that objects you created for one app are also useful in others, and you start getting better code re-use as well. So the new app has part of the work already done, and is using time-tested code: software is built faster with fewer bugs.
People will tell you various things about OOP, from various perspectives. But if you want to form your own opinion, rather than take someone else's, then I suggest reading Bertrand Meyer's "Object-Oriented Software Construction".
Essentially, he takes non-OOP programming techniques, and analyses their basic flaws. He then derives an alternative technique which addresses those flaws. Put another way, he derives OOP from first principles. It's a marvellous piece of work, and very convinving.
Read it, you'll learn the why, when and what in a way that you can back up with reasoning.
Objects help encapsulate complexity. For most PHP programming, it's impossible to write good, clean code for any reasonably complicated application. Writing OO PHP helps you put that code into its own box, isolating it from everything else. This has several benefits.
As long as your object has clearly defined inputs and outputs, the way that the object does what it does doesn't matter at all - storing/retrieving data could go from flat file to XML to memcache to MySQL to Oracle, and you only ever have to concern yourself with one single object.
As long as your object has clearly defined inputs and outputs, you can completely replace it with another object that has the same inputs/outputs. Decide at runtime whether you want MySQL, Postgres, memcached, or HTTP POST/GET requests to a sketchy server in Indonesia.
OO makes unit testing easier. If you can define what a specific object should do (i.e what results it should give you for a given input) then you can easily write code to test thousands of values against that code and check the results, and you'll know instantly if something breaks.
The more of your code you 'hide' in objects, the less of it you have to see when you're using that functionality. I wrote a polling application once in PHP that handled all aspects of polling - database interaction, poll generation, voting, ranking, sorting, and displaying - and I only needed one line of code on my website (Poll::Display()) to implement the entirety of what the app could do - which made maintaining my homepage far easier.
Keep one thing in mind - OO in PHP (even PHP5) isn't very good OO compared to a language like Python or Ruby. The everything-is-an-object model in Python is what made me OO programming really click for me - and as a former PHP programmer (and doubly-certified Zend engineer), I strongly recommend exploring Python's OO if you want to understand what OO is all about. It will help you write better PHP code, at the very least.
Yes, if you really get it.
It helps you visualize how parts of a larger system can interact with each other. It's very useful at the design level.
If you are just writing a few lines of code, the only benefit you will get is that it is generally a little easier to use a library broken into well-designed objects than just functions.
To make good use of it, you also need to follow sound OO design practices. Always encapsulating ALL your data, using many small classes, never large "catch-all" classes. Having the class do your work for you instead of asking it for data and doing the work outside the class, etc.
It's probably not going to help you much for a while, and possibly never if you are always doing small websites (I can't say this for sure, I don't really do php), but over time and on large projects it can be invaluable.
One thing no one has mentioned is that OO code facilitates writing readable code:
sherry.changePhoneNumber();
phoneCompany.assignNewPhoneNumberTo(sherry);
sherry.receive(new PhoneNumber().withAreaCode("555").withNumber("194-2677"));
I get a strange satisfaction from such aesthetics.
The huge win for me is inheritance, or making an object that behaves almost exactly like another but with a few differences. Here's a real-world example from my office:
We needed code to process TIFF files that a customer sent to us, convert them to a standard format, insert some information about the file into a database, then send a result email. I wrote this in a set of classes (in Python, but the idea is the same). The "fetcher" class got emails from a POP3 mailbox and handed them to a "container" class which knew how to read attachments from an email. That class handed each image off to a "file object" class that did the necessary processing.
Well, one day we got a customer who wanted to send PDF files. I subclassed the "TIFF file object" class and rewrote the "normalize" function to take a PDF as input instead, but left every other bit of code untouched. It worked the first time and I was pretty pleased.
A change to our mailserver meant that I needed to fetch emails via IMAP. Again, I subclassed the "POP3 fetcher" so that it could speak IMAP. Problem solved.
Another customer wanted to mail us CDs, so I subclassed the "email container" class with a "filesystem directory" class. Voila - done.
In each of those cases, the new code was 95% similar to the old code. For example, the "TIFF file object" class has about 15 methods. The "PDF file object" class defines exactly one: the method that converts files in a specific format into our standard. All others it gets from its parent class.
Now, you can definitely do the same kind of stuff procedurally, such as by writing:
if fileobjecttype == 'TIFF':
data = <snip 30 lines of code to read and convert a TIFF file>
elif fileobjecttype == 'PDF':
data = <another 45 lines to read a PDF>
elif fileobjecttype == 'PNG':
data = <yep, another one>
The biggest difference is that I believe you can make OOP look much cleaner and more organized. My PDF class looks like:
class PDFReader(GenericImageReader):
def normalize(self):
data = <45 lines to read a PDF>
and that's it. You can tell at a glance that it only does one thing differently than the class it inherits from. It also forces you - or at least strongly encourages you - to make clean interfaces between the layers of your application. In my example, the PDFReader has no idea and doesn't care whether its image came from a POP3 mailbox or a CD-ROM. The POP3 fetcher knows absolutely nothing about attachments, since its job is merely getting emails and passing them along. In practice, this has allowed us to do some pretty amazing things with the absolute minimum amount of coding or redesign.
OOP isn't magic, but it's a pretty fantastic way to keep your code organized. Even if you don't use it everywhere, it's still a skill that you really should develop.
There was a time, back when i first started programming, that i wrote user-oriented code. It worked great, but was hard to maintain.
Then, i learned OO, and the code i wrote become easier to maintain, easier to share between projects, and life was good... for everyone except my users.
Now, i know the true silver bullet of computer programming. I write OO code, but first i objectify my users. Treating people as objects may seem rude at first, but it makes everything much more elegant - you get to write all of your software to work with clearly-defined interfaces, and when a user sends an unexpected message you can merely ignore it, or, if marked with a flag signifying sufficient importance, throw an exception at them.
Life, with OO, is good...
I would argue that OOP suits those who think in 'objects', where an object consists of data as well as the functions that operate on that data.
If you tend to think of functions and the data they operate on as separate things, then you are a procedural programmer.
If you tend to think of functions and the data they operate on as being connected, then you are an object-oriented programmer.
I'd caution against going out and learning about patterns. In order to do object-oriented programming well, you need to teach yourself to think like an object-oriented programmer. You'll need to get to the point where you understand and can name the benefits of:
Encapsulation
Classes vs instances/objects
Inheritance and polymorphism
It will help you to be a better programmer only in the sense that the more styles of programming a programmer knows, the more range in his repertoire for solving problems and writing elegant code. You cannot go off and write all your code object-oriented and automatically have good code, but if you really understand how OOP works, and you're not just copy-pasting some popular design patterns of the day, then you can write some pretty good code, especially when writing a large application.
It seems everybody is responding to your question literally, i.e., the specific benefits/drawbacks of OO.
You should learn OO, but not because OO has any specific magic that you need.
The more general form is:
Q: "Should I learn (OO, FP, concurrent, logic-based, event-driven, ...) programming?"
A: "Yes, learning a new paradigm is always useful, even if you don't use it directly every day."
I would put it this way: If you write anything complex, you should encode the concepts you think in, rather than trying to think in concepts that are somehow native to the language you are using. This way you make less bugs. The formalization of those concepts is called design.
Functional programming lets you define concepts that are associated with verbs, since each function is essentially a verb (e.g., print()). OO programming, on the other hand, lets you also define concepts associated with nouns.
To elaborate on Joeri's answer a little:
The International Organisation for Standardization defines encapsulation as, 'The property that the information contained in an object is accessible only through interactions at the interfaces supported by the object.'
Thus, as some information is accessible via these interfaces, some information must be hidden and inaccessible within the object. The property such information exhibits is called information hiding, which Parnas defined by arguing that modules should be designed to hide both difficult decisions and decisions that are likely to change.
Note that word: change. Information hiding concerns potential events, such as the changing of difficult design decisions in the future.
Consider a class with two methods: method a() which is information hidden within the class, and method b() which is public and thus accessible directly by other classes.
There is a certain probability that a future change to method a() will require changes in methods in other classes. There is also a certain probability that a future change to method b() will require changes in methods in other classes. The probability that such ripple changes will occur for method a(), however, will usually be lower than that for method b() simply because method b() may be depended upon by more classes.
This reduced probability of ripple impacts is a key benefit of encapsulation.
Consider the maximum potential number of source code dependencies (MPE - the acronym is from graph theory) in any program. Extrapolating from the definitions above, we can say that, given two programs delivering identical functionality to users, the program with the lowest MPE is better encapsulated, and that statistically the more well-encapsulated program will be cheaper to maintain and develop, because the cost of the maximum potential change to it will be lower than the maximum potential change to the less well-encapsulated system.
Consider, furthermore, a language with just methods and no classes and hence no means of information hiding methods from one another. Let's say our program has 1000 methods. What is the MPE of this program?
Encapsulation theory tells us that, given a system of n public nodes, the MPE of this system is n(n-1). Thus the MPE of our 1000 public methods is 999,000.
Now let's break that system into two classes, each having 500 methods. As we now have classes, we can choose to have some methods public and some methods private. This will be the case unless every method is actually dependent on every other method (which is unlikely). Let's say that 50 methods in each class is public. What would the MPE of the system be?
Encapsulation theory tells us it's: n((n/r) -1 + (r-1)p) where r is the number of classes, and p is the number of public methods per class. This would give our two-class system an MPE of 499,000. Thus the maximum potential cost of a change in this two-class system is already substantially lower than that of the unencapsulated system.
Let's say you break your system into 3 classes, each having 333 classes (well, one will have 334), and again each with 50 public methods. What's the MPE? Using the above equation again, the MPE would be approximately 482,000.
If the system is broken into 4 classes of 250 methods each, the MPE will would be 449,000.
If may seem that increasing the number of classes in our system will always decrease its MPE, but this is not so. Encapsulation theory shows that the number of classes into which the system should be decomposed to minimise MPE is: r = sqrt(n/p), which for our system is actually 4. A system with 6 classes, for example, would have an MPE of 465,666.
The Principle of Burden takes two forms.
The strong form states that the burden of transforming a collection of entities is a function of the number of entities transformed. The weak form states that the maximum potential burden of transforming a collection of entities is a function of the maximum potential number of entities transformed.
In slightly more detail, the burden of creating or modifying any software system is a function of the number of program units created or modified.
Program units that depend on a particular, modified program unit have a higher probability of being impacted than program units that do not depend on the modified program unit.
The maximum potential burden an modified program unit can impose is the impacting of all program units that depend on it.
Reducing the dependencies on an modified program unit therefore reduces the probability that its update will impact other program units and so reduces the maximum potential burden that that program unit can impose.
Reducing the maximum potential number of dependencies between all program units in a system therefore reduces the probability that an impact to a particular program unit will cause updates to other program units, and thus reduces the maximum potential burden of all updates.
Thus, encapsulation is a foundation stone of object orientation and encapsulation helps us to reduce the maximum potential number of dependencies between all program units and to mitigate the weak form of the Principle of Burden.
I'm a long-time procedural PHP programmer who occasionally dabbles in object oriented PHP. Joel's answer above is an excellent summary of the benefits. In my opinion, a subtle secondary benefit, is that it forces you to better define your requirements from the start. You have to understand the relationships between the objects and the methods that will be acting upon them.
A good book to help with the transition is Peter Lavin's "Object-Oriented PHP".
A large system, such as Wordpress, Drupal, or XOOPS, uses OOP concepts. You can see the benefits of their use there. Code reuse, modularity, maintainability, and extensibility.
You have the ability to modify parts of objects and it affects the entire application; no searching to replace every spot you did some operation (and possibly missing it).
You can reuse objects all over, saving an awful lot of copying and pasting. Patching a bug requires patching the one object, not 16 pages of code that all do the same thing.
When you encapsulate the logic and "hide" the implementation, it's easier to use the objects, both for you 6 months from now when you've forgotten why you did something, and for the nest guy or gal who uses your code. For example, all you do to loop through posts in Wordpress is call a function. I don't need to know how it works, I only need to know how to call it.
OOP is really procedural code wrapped in object methods/functions. You do still need to know how to write decent linear code in order to implement methods and functions of objects. It just makes it far easier to reuse, scale, fix, debug, and maintain your things.
http://www.onlamp.com/pub/a/php/2005/07/28/oo_php.html
I would say there are two primary benefits:
Encapsulation: code in libraries that shouldn't be called from outside the library can be hidden, preventing misuse, and easing changes to the internal structure of the library while preserving the external interface. In a good OO design, changes are introduced more easily once the code is complete.
Abstraction: instead of dealing with arrays of arrays you're dealing with employees, departments, and so on. This means you can focus on the business logic, and write fewer lines of code. Fewer lines means fewer bugs.
Reuse I wouldn't strictly qualify as an OO benefit, because in a purely procedural model smart library organization lets you reuse code as well.
On the other hand, using lots of objects in PHP tends to decrease performance compared to a procedural model, because there is too much object construction overhead for every request. Finding a good balance between procedural-style and oo-style code is imperative.
To learn OO in PHP I'd recommend try to use some good written OO PHP framework.
You may want to look at Zend Framework.
I am a PHP aswell, although I do have a strong OOP background, I would say the best book on using OOP with PHP has to be PHP 5 Objects Patterns and Practice
One of the best thing that I did with OOP in PHP is the class generator.
In any given table, it will involve almost the same SQL operations:
insert
update
select
delete
exists (check if a row exists)
search
list
Now I don't have to write all these SQL statements anymore, except on special conditions. Not only I've cut down coding to 1 minute in doing above, I've also saved time from debugging codes.
So whenever there are changes to the table structure, I simply regenerate the class.
Probably you should try the same as it works for me and my customers like it!

Categories