When I look at some functions on the PHP homepage, they give two different styles of using it: procedural, and object oriented. I know that OOP is real popular, but why so? What do both styles offer, and what makes one better than the other?
Jeff Mott
12-12-2008, 06:18 PM
In OO, data and the functions that operate on that data are bound together as a unit; it's easier to reuse and extend software; you can define interfaces; you can hide information and functions the rest of the system doesn't need; and many other things. There's plenty to discover about OO from books and from google with some research.
scragar
12-12-2008, 06:23 PM
OOP is fantastic, and much more efficient at reusing code, so I'm all for it, it does have some draw backs, it's often slower, uses more ram(unless you are using lot's of the same object, when it suddenly starts becoming smaller) and takes a bit more effort to write.
I love it though, because it's very efficient at reusing, and expanding upon code, using a simple example:
class shape{
private $points = array();
public function __construct($points){
foreach($points as $k=>$v)
$this->points[$k] = (float)$v;
}
}
class square extends shape{
public function __construct($topLeft, $bottomRight){
parent::__construct(Array($topLeft, $bottomRight));
}
public function draw(){
// blah
}
}
In this way I can change the __construction function for all of my shapes in one parent object, such is the power of inheritance.
NogDog
12-12-2008, 10:16 PM
Just to add to the above, the benefits of OOP increase as the size of the application increases. With very large applications, you'll likely end up saving a lot of time by using OOP (assuming you use it correctly) as debugging, modifying, and re-factoring become easier with OO code compared to procedural code. In fact, just writing the initial code actually becomes easier as it's simpler to keep the overall application design under control.
For the very simplest of tasks, procedural code is fine. If all you want to do is add a dynamic copyright date at the bottom of your web page, there's no need to define a CopyrightDate class, instantiate it, and call a method when all you really need is:
But if you want to build your own blogging system, for example, OOP will make for a much more clearly structured application that is easier to maintain, modify, upgrade, etc. But simply using classes and objects does not make it object-oriented: it's how you use them.
You might consider picking up PHP Objects, Patterns, and Practice (http://www.apress.com/book/view/9781590599099) by Matt Zandstra as a good introduction to how to "think" in an object-oriented way.
toicontien
12-13-2008, 11:35 AM
I second "PHP Object, Patterns and Practice." Great book on OOP in general, flavored with PHP. The book also has great references to other OOP books in different programming languages, as many of the programming patterns covered are language agnostic.
Joseph Witchard
12-13-2008, 06:19 PM
Is OO the future of all programming languages? So far, the only programming languages I have experience in are Visual Basic, Java (though very little), and the web programming languages, PHP, JavaScript (very little).
NogDog
12-13-2008, 06:35 PM
OOP is the present of programming languages. Java is designed from the ground up to be object-oriented; in fact, every piece of code in a Java program must be part of a class (though that does not stop you from writing what is still essentially procedural code if you wanted to). The future of programming is probably still a vague concept in some smart guy's mind. ;)
scragar
12-13-2008, 06:39 PM
As I said, oop is very much about reusing code, procedural code, on the other hand, is much more about the flow of logic.
// do normal stuff, include the class
$form = new form('POST', $_SERVER['PHP_SELF']);
$form->addRequired('text', 'username', 'Username: ');// type, name, label
$form->addRequired('password', 'password', 'Password: ');
$form->addSubmit('Log in');
$loggedIn = false;
if($form->requiredSet()){
// check login information
$username = $form->mysqlSafe('username');
$password = md5($form->dataSafe('password'));
}
if( ! $loggedIn)
$form->show();
To get to the same point in procedural code would take much more work:
$loggedIn = false;
if(isset($_POST['username']) && !empty($_POST['username']) &&
isset($_POST['password']) && !empty($_POST['password'])){
$username = mysql_real_escape_string(get_magic_quotes_gpc()?strip_slashes($_POST['username']):$_POST['username']);
$password = md5(get_magic_quotes_gpc()?strip_slashes($_POST['username']):$_POST['username']);
//...
}
if( ! $loggedIn){
echo <<<HTML
<form action='{$_SERVER['PHP_SELF']}' method='POST'>
<p><label for='username'>Username: </label><input type='text' name='username' id='username'></p>
<p><label for='password'>Password: </label><input type='password' name='password' id='password'></p>
<p><input type='submit' name='login' value='Log in'></p>
</form>
HTML;
}
I know which one I would rather work with.
Stephen Philbin
12-13-2008, 07:38 PM
I was actually going to buy the PHP 5 version of that book you liked to, Charles, but I got redirected to an incredibly annoying site when I hit the 'buy' button.
I started learning about OOP in PHP5, but to this day It just doesn't seem to click with me. I get it in Java. It all seems to go quite nicely. But when I go for OOP in PHP, it just feels like it doesn't fit. I think I know the main reasons why, but I wanted a good book that discussed OOP in PHP5 to be sure I'm not missing something obvious.
For me the two things that make it feel like OOP doesn't quite sit right with PHP is that A) I don't think my website is a large enough 'project' yet to reap the benefits of OOP, and also that a PHP application is not stateful. It's really just fragments of an application the are re-invoked over and over again.
The way I think of it is that with a Java application most of the main classes that do the heavy lifting (and therefore usually are the most expensive to instantiate) are instantiated only very occasionally (probably once) and then data flows through the application with relative simplicity thereafter, but with PHP it isn't the same. In PHP, processing a single piece of input usually means re-instantiating everything in the PHP script. Rather than having them all ready and standing by to process input at any time like you would in a Java (or most other OO-based language) desktop application.
Joseph Witchard
12-14-2008, 02:35 AM
The future of programming is probably still a vague concept in some smart guy's mind.
Like Bill Gates?:D
*gets ready for the cries of protest to his comment*
(I don't know how people on this forum feel about Bill Gates, I just know that many of them hate Microsoft:p)
But seriously, thanks for the help:) And I'll definitely look into getting that book. I already know that I'm getting a PHP book that I really wanted for Christmas, so maybe I'll pick the one about OOP if I get any cash.
Wisest Guy
12-14-2008, 03:48 AM
The difference is naming.
// do normal stuff, include the class
$form = new form('POST', $_SERVER['PHP_SELF']);
$form->addRequired('text', 'username', 'Username: ');// type, name, label
$form->addRequired('password', 'password', 'Password: ');
$form->addSubmit('Log in');
In procedural code:// do normal stuff, include the class
$form = newForm('POST', $_SERVER['PHP_SELF']);
formAddRequired($form, 'text', 'username', 'Username: ');// type, name, label
formAddRequired($form, 'password', 'password', 'Password: ');
formAddSubmit($form, 'Log in');
$loggedIn = false;
if(formRequiredSet($form)){
// check login information
$username = formMysqlSafe($form, 'username');
$password = md5(formDataSafe($form, 'password'));
}
if( ! $loggedIn) // Never saw this set to anything other than false, but I'll assume it works as intended. :p
formShow($form);
Of course having "form" prefix every function name is not mandatory, but it is redundant if done, seeing as the first argument is already known to be a form.
OOP is more human.
felgall
12-14-2008, 03:40 PM
There are a dozen or so completely different approaches to programming of which object oriented and procedural are the two most commonly used at present. Most individual languages usually support only one or two of these approaches (for example Java only supports OOP while PHP supports both OOP and procedural).
ayvegh
12-19-2008, 03:04 PM
I find OOP to be the bane of my existence in PHP. :)
I wrote a simple templating engine to make my life simple, and now the code used to generate my homepage (http://ayvegh.com) looks like this:
<?php
require_once('includes/init.php');
$template->set_title('home');
$welcome = <<<EOP
<p>
Welcome to ayvegh.com<br />
There are still some things under construction, but feel free to have a look around.
</p>
EOP;
$template->add_post('Welcome', $welcome);
?>
Pure, unadulterated, simplicity. ;)
OOP is the here, now, and forever. :D
ayvegh
xvszero
12-19-2008, 03:32 PM
I think I need to learn OOP (beyond the barely learning it in a classroom background I have.) I'm still sort of somewhat unclear on the benefits. Generally if I'm writing a function I know I'll need to reuse I just have it take in a lot of input and create whatever needs to be creating dynamically based on that input. But I guess OOP would make it easier to scale the function without needing a ton of additional input?
NogDog
12-19-2008, 07:53 PM
It's not enough to just learn the syntax of class definitions and how to invoke objects and their methods. You need to learn to think in an object-oriented way. It might help to study some of the well-known OOP patterns in order to see how things like interfaces, abstraction, inheritance, etc. actually work together in a well-designed OO application. For PHP, in addition to the book I mentioned above, there are a number of web sites that discuss PHP OOP design patterns, such as http://www.fluffycat.com/PHP-Design-Patterns/ or the many articles at zend.com: http://devzone.zend.com/tag/Design%20Patterns.
bluestartech
12-19-2008, 08:35 PM
OOP in perl is sweet, when done properly it saves hours with re-usuable code, and perfrormance under mod_perl is second to none
felgall
12-20-2008, 03:29 PM
After many years of using structured programming and rule based programming it took me about three years to really start to think properly in terms of object oriented programming. Each type of programming is very different from each of the other types and it takes far longer to learn a new programming style than it does to learn a half dozen new languages that follow a style that you already know.
NogDog
12-20-2008, 03:44 PM
After many years of using structured programming and rule based programming it took me about three years to really start to think properly in terms of object oriented programming. Each type of programming is very different from each of the other types and it takes far longer to learn a new programming style than it does to learn a half dozen new languages that follow a style that you already know.
I think that part of the problem with PHP is that virtually everyone who learns it starts by learning purely procedural programming in PHP. Then at some point they decide they need to learn how to program objectively and have to fight with habits and ingrained mind-sets. I wonder how much easier it would be if new programmers simply dove in at the OOP end of the pool from the start instead of treating it as an "advanced concept" to be learned as an add-on to PHP programming?
Joseph Witchard
12-21-2008, 03:37 PM
I think that part of the problem with PHP is that virtually everyone who learns it starts by learning purely procedural programming in PHP. Then at some point they decide they need to learn how to program objectively and have to fight with habits and ingrained mind-sets. I wonder how much easier it would be if new programmers simply dove in at the OOP end of the pool from the start instead of treating it as an "advanced concept" to be learned as an add-on to PHP programming?
Might be easier if they learned something like Java first, since it's already set up as OOP. I know that learning Visual Basic in school helped me understand the programming I do a lot better.
ayvegh
12-21-2008, 06:35 PM
Might be easier if they learned something like Java first, since it's already set up as OOP. I know that learning Visual Basic in school helped me understand the programming I do a lot better.
Or JavaScript, since it's essentially OOP, but only if that fact is explained and expounded upon. ;)
Joseph Witchard
12-22-2008, 01:45 AM
I dunno. I've been in the beginning phases of studying JavaScript, and to me, it seems more or less the same as procedural PHP (with a different syntax, of course). From what I remember about Java when I took it in school (before leaving due to health circumstances), it threw you into OOP right from the beginning.
Shorts
12-23-2008, 11:26 AM
For me, the biggest OOP page I wrote was the search engine for the site I work at. Designed it from the ground up and definitely planned on what was to be done.
Idea was to get numbered results depending on different filters.
E.g.
$search->remove_filters();
foreach($states as $state) {
$search->filter('state',$state);
$results = $search->generate(true); # true is set so it only gives me COUNT(*)
if($results) {
# DO STUFF
}
}
when done properly it saves hours with re-usuable code,
The biggest thing to understand is that as developers, we are not building the Taj Mahal. What we build today does not need to withstand the tests of time for centuries. Code is disposable. Spend countless time "perfecting" your OO classes or "make-it-work" with procedural code. I choose procedural as I always know "exactly what I am getting".
Some advocate OO programming and that is okay, but I find it to be more work than procedural coding for modern web solutions. Not only more work, but OO also obfuscates what is "really going on". If you are a true programmer, you want to know "what is going on" in a transparent fashion. I feel OO removes this transparency.
Shorts
12-29-2008, 12:10 PM
Webnerd. I would agree with that to an extent. When I freelanced (or on private ventures) most of my coding is Procedural, since I know all the functions/variables in use and they usually aren't heavily involved. However, at work where there are several other developers and much bigger tasks, OO is the way to go so we're not overwriting codes and also giving each other easy to use functions.
On the second part, I never saw OO as obfuscating code. I've always seen it as being a way to store massive data, change it on the fly, and then generate the results that it was programmed to do.
On the flip side though, one of the guys here always uses Classes but has no idea what OO is so his stuff usually does become obfuscated... Obfuscation isn't due to the language, its due to the programmer. (and some of us do it on purpose!) :D
webdeveloper.com
Copyright Internet.com Inc., All Rights Reserved.