Why use PHP OOP over basic functions and when?

PhpOop

Php Problem Overview


There are some posts about this matter, but I didn't clearly get when to use object-oriented coding and when to use programmatic functions in an include. Somebody also mentioned to me that OOP is very heavy to run, and makes more workload. Is this right?

Let's say I have a big file with 50 functions. Why will I want to call these in a class? And not by function_name()? Should I switch and create an object which holds all of my functions? What will be the advantage or specific difference? What benefits does it bring to code OOP in PHP? Modularity?

Php Solutions


Solution 1 - Php

In a lot of scenarios, procedural programming is just fine. Using OO for the sake of using it is useless, especially if you're just going to end up with POD objects (plain-old-data).

The power of OO comes mainly from inheritance and polymorphism. If you use classes, but never use either of those two concepts, you probably don't need to be using a class in the first place.

One of the nicest places IMO that OO shines in, is allowing you to get rid of switch-on-type code. Consider:

function drive($the_car){

    switch($the_car){

      case 'ferrari':
          $all_cars->run_ferrari_code();
          break;

      case 'mazerati':
          $all_cars->run_mazerati_code();
          break;

      case 'bentley':
          $all_cars->run_bentley_code();
          break;
    }
}

with its OO alternative:

function drive($the_car){

    $the_car->drive();
}

Polymorphism will allow the proper type of "driving" to happen, based on runtime information.


Notes on polymorphism:

The second example here has some premisses: That is that all car classes will either extend an abstract class or implement an interface.

Both allow you to force extending or implementing classes to define a specific function, such as drive(). This is very powerful as it allows you to drive() all cars without having to know which one you're driving; that is because they're extending an abstract class containing the drive() method or implementing an interface forcing the drive() method to be defined.

So as long as you make sure that all your specific cars either extend the abstract class car or implement an interface such as canBeDriven (both of which must declare the drive() method) you can just call the drive() method on an object which you know is a car (but not what type of car) without fear of it not being defined, as PHP will throw fatal errors at you until you define those methods in your specific car classes.

Solution 2 - Php

I'll try to keep my answer as an addition because the answers by Majd Taby and Coobird are really good.

I was mostly a procedural programmer for several years and didn't fight against OOP programming, but never really saw much relevance...that is until I started working on a team and building more important and complex projects.

OOP really shines, in my opinion, when you need to write lean, easily maintainable code for more complex applications. And mind you, not in every situation, but there are some where procedural just won't work that well.

Most of my examples of great OOP implementations are for projects where I had several things that were all related but all slightly different. Sites with lots of forms, lots of users, lots of products etc.

They all have similar behaviour names like print(), update(), etc...but by encapsulating them as objects and varying the methods' implementations in the classes I can make my code at runtime very simple and clean throughout the site. Also, and this one was key, despite having different behaviours, I could work with different objects using the same method calls throughout the entire application. It allows a second developer to work on actual implementation while I work on deeper code.

I don't know if that helps any but speaking as someone who was in your situation not too long ago, I love OOP.

Solution 3 - Php

Using an object-oriented programming approach rather than a procedural programming approach in a program doesn't really depend on the language (be it PHP or not), but on the type of problem you are trying to solve.

(I'm just going to use pseudocode in my examples as I am not too familiar with PHP.)

For example, if you have a program where you are just performing a bunch of functions in order, then procedural is going to be fine. For example, if it's a simple string manipulation program, a procedural approach would suffice:

perform_truncation(my_string, 10)
to_upper(my_string)
perform_magic(my_string, hat, rabbit)

However, if you're going to deal with many different items (such as files, or any other representation of, well, objects) then an object-oriented approach would be better.

For example, if you had a bunch of Cars and wanted them to drive, then in procedural, you may do something along the line of:

drive_car(first_car)
drive_car(second_car)

Where as, in OOP, the Car can drive itself:

RedCar myRedCar();
BlueCar myBlueCar();

myRedCar.drive();
myBlueCar.drive();

And, as each car is a different class, their behavior can be defined differently. Furthermore, they may be both subclasses or Car they may have common functionality.

It really comes down to the type of problem which makes either procedural approach better than object-orientated and vice versa.

Aside from the issue of procedural or object-oriented, it may be a kind of "code smell" to have one source file with many functions. This can also be said about classes which contain many functionalities which may be better performed as separate functions in separate classes.

The issue here may be of code organization rather than deciding to pick procedural or object-oriented programming. Organizing functions into separate source files may be what's needed here than to abandon the procedural approach to writing the program.

After all, there are plenty of programs written in the procedural programming approach which is well-written and easy to maintain.

Solution 4 - Php

> Lets say I have a big file with 50 > functions, why will I want to call > these in a class? and not by > function_name(). Should I switch and > create object which holds all of my > functions?

Moving to OOP should not been seen as a simple 'switch' in the way you describe above.

OOP requires a completely different way of thinking about programming which involves rewiring your brain. As rewiring a brain doesn't happen overnight many people are unwilling to expose themselves to the required rewiring process. Unfortunately the rewiring is going to take an investment in time and effort: research, tutorials, trial and error.

It really involves taking a step back and learning about the concepts behind OOP but the payback will be well worth it speaking as someone who went through this process in the pre www days.

After you 'get it' and follow OOP best practices in your everyday you'll be telling others how your programming life has changed for the better.

Once you really understand OOP you will have answered your own question.

Solution 5 - Php

If you have 50 functions instead of 50 static methods into Utilities class, you "pollute" the global namespace.

Using a class with 50 static methods, method names are local to your class.

Solution 6 - Php

I can't say which one is better. but in my experience you can have better code management using OOP. you know which code is where, what functionality is defined in which file, etc. about the runtime overhead for OOP I read somewhere (and I think it is true) that if you write a bad code in classic functions, and the same bad code in OOP, the function version works better. so if your code is not written bad, there is no proof that OOP is keeping your application slow. also remember that these "slow" and "overhead" stuff are all measured in milliseconds. so if your application is not serving a lot of users (like more than 100 users in a minute), you might not feel any difference.

Solution 7 - Php

OOP allows you to create structured containers of code, called classes, which can be parents/children of one another. This can help with building an application as it is easier to maintain and can, if done properly reduce code redundancy. OOP does add a bit overhead but it isn't really noticeable and is outweighed by the unmaintainablity of procedural code. If your writing a big app, def go OO, especially if it is going to be worked on by many people.

For example, say you are designing a simple website. You could create a Page object. The page object is responsible for going to the database and getting various settings for the page, such as meta data, title tags, or even the number of certain "components" on the page and their type (such as a calendar control, a widget, etc).

Then, you can create another class, say Index, that extends Page. Index would be the index or home page. If you had a catalog of products, you could have Catalog class extend page. Since both your catalog section and your homepage need to get data from the database concerning the metadata of the page and the basic construction of the page, having 1 object that does it already for you helps. In both of these situations, page does all the work and gets the page data from the database, loads it into variables, which are then accessible in both your index class and your catalog class. You don't have to write code to go into the database and get it again in each page you write.

Now there are other ways to do this procedurally, such as with an includes. However, you will find yourself making less mistakes and errors. For example, you can define an abstract method in your Page class. This means that this method MUST be defined in any object that extends it. So say you created a setPageAttributes() function as abstract in your Page class. When you do this you create an empty function. When you create your index class, you HAVE TO create a setPageAttributes() function (with the intent on filling it in, such as accessing the variables defined in the Page class and using it to set the actual elements on the page, template, or view you are using) or you get a PHP error.

If you are working with other people to get your project written, abstract methods will tell the person, "Hey, you need to define these functions in any code you write". This forced the application to be consistent.

Finally, you cannot go to frameworks such as MVC formats if you do not do OOP. While it is not necessary to go to MVC and there is some debate, it does separate out all the components of the application and is necessary in environments where many people (designers, coders, marketing employees) work on the same code.

Solution 8 - Php

Use of the oop gives you following benefit:

  1. Structuring
  2. Reusability
  3. Easy Maintenance
  4. Encapsulation of the Data

Coming to the point of making big file with 50 function. You can do that but when it comes to the flow of the function and how the data data will be bind between every function will be a biggest problem.

Also for the future maintenance if you want to replace the biggest chunk of the flow, trust me you have to go to every function and play around it. Also you never know how your functions are used in other part of the code. So Object Oriented programming is always advisable.

Solution 9 - Php

The accepted answer seems to have neglected to state that it is possible to call functions based on a variable name such as in the example herew:

function drive($the_car){
	$the_car();
}

Admittedly there would need to be a function for each car in this instance but it's a lot more efficient than the suggested switch statement.


Additional variables can be supplied easily as such:

function operate($the_car,$action){
	$the_car($action);
}

function ferrari($action){
	switch($action){
		case 'drive':
			echo 'Driving';
			break;

		case 'stop':
			echo 'Stopped';
			break;
			
		default: return;
	}
}


operate('ferrari','drive');

There is a switch statement here but it's to supply additional functionality that was not in the original example so it's in no way a contradiction.

Solution 10 - Php

The OOPs concept is used in PHP, so as to secure the code. As all the queries are written in function file instead of code file so no one can easily hack our code. So it is better to use classes in PHP instead of directly writing the queries.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCodex73View Question on Stackoverflow
Solution 1 - PhpMajd TabyView Answer on Stackoverflow
Solution 2 - PhpjerebearView Answer on Stackoverflow
Solution 3 - PhpcoobirdView Answer on Stackoverflow
Solution 4 - PhpVolksmanView Answer on Stackoverflow
Solution 5 - PhpLuc MView Answer on Stackoverflow
Solution 6 - PhpfarzadView Answer on Stackoverflow
Solution 7 - PhpDanView Answer on Stackoverflow
Solution 8 - PhpAnkur Kumar SinghView Answer on Stackoverflow
Solution 9 - PhpAndy GeeView Answer on Stackoverflow
Solution 10 - PhpKirandeep KaurView Answer on Stackoverflow