Simple Explanation PHP Oop VS Procedural

simple explanation PHP OOP vs Procedural?

Background: You asked for a "simple explanation" which suggests:

  1. You want a no-nonsense overview without jargon
  2. You want something that will help you learn from the beginning
  3. You have discovered that no two people ever answer the question the same way, and it's confusing. That's the reason you are here asking for a simple explanation. Yes?

Short No-Jargon Answer:

  1. Many introductory explanations jump quickly into "OOP real world" examples. Those can tend to confuse more than help, so feel free to ignore that for now.
  2. You can think of source code simply as "chunks" of functionality, that just happen to be saved to individual files.
  3. There are different ways of organizing those "chunks"; depending on things like conventions of the programming language, the background and training of the developer(s), or just plain old personal preference.
  4. OOP and Procedural programming are simply two main, generally-recognized methodologies, for how to organize and arrange those "chunks" of code.

Long No-Jargon Answer:

Procedural vs OOP is just one aspect of a fundamental issue of computer programming: how to make your code easy to understand and a piece of cake to professionally maintain. You can actually write "Procedural" code that follows some of the principles of OOP, so the two are not necessarily opposites.

Your understanding will really grow once you learn other object-oriented programming languages, among which, PHP is a "new kid on the block".

Here is a quick overview of what you will learn as you build experience:

  • You can write PHP source code that does useful tasks

  • You can organize useful tasks into "chunks" of code

  • You can think of "chunks" of code independently of the individual files where they are saved

  • Sometimes those "chunks" of code will behave differently based on parameters you pass in

  • Chunks of code that accept parameters are called "Functions"

  • Functions can be "chunked" together, and there are different ways of doing this:

    • For example: you could have just one big PHP file with all the functions you have ever written in your entire life, listed in alphabetical order by function name
    • For example: you could have multiple PHP files with functions that are chunked together by subject matter [e.g., functions for doing basic string manipulation, functions for processing arrays, functions for file input/output, etc]
  • OOP is a special way of "chunking" Functions together into a "Class"

  • A Class is just another level of "chunking" code together so that you can treat it as a unified whole

  • A Class can be thought of as a "chunking" of methods and properties

    • methods are simply functions that are logically related to one another in some meaningful way. The words "method" and "function" are basically two different terms for the same thing.
    • properties are simply data values that are related to the class. These are values that are intentionally non-isolated to any individual function, because more than one of the functions in the class should have access to them.
      • For example: if your class has a bunch of methods for doing astronomy, properties of the class might be the values for certain famous numbers that all astronomy methods need to know about (like Pi, the speed of light, the distance between specific planets, etc.).
    • This is where most OOP explanations get confusing because they branch off into "real world examples" which can quickly get off-topic. Often, "real world" is a euphemism for the ontological perspectives of a particular individual or group. That tends to be useful only once you already understand the concept well enough to teach it to someone else.
    • To understand OOP without confusion, you can skip the "real world" examples for now, and just focus on the code. A Class is simply a way to store functions (aka methods) and properties (aka data) as PHP code in one or more related "chunks" where each individual "chunk" deals with a specific topic or piece of functionality. That's all you need to know in order to get started.
  • A Class is useful because it allows you to organize your code at a very high level in a way that makes it easy for you to understand, use, and maintain.

  • When someone has written a lot of functions, and organized them into a lot of Classes, and gotten those to work together in some cool way, they package the whole thing together and call it a "Framework".

  • A Framework is just the next-highest level of "chunking" (including coding style and conventions) that one or more people agree on because they like the way the code is organized and it suits their working style, preferences, values, plans for world domination, etc.

See also

  • OOP appeal

Procedural PHP vs Object Oriented PHP

Even thou it is 2014, you are still allowed to wash your dishes by hand, communicate with all your friends only in person, landline phone calls or letters send by the local postal service.
And you might feel incredibly well doing so.

But if you try to host a lot of dinner parties for a lot of people and organise important projects with a lot of people from remote destinations, having hard deadlines, you might consider getting a modern dishwasching machine and a smartphone.

Same goes for OOP vs. procedual. If you are just adding a tiny piece of functionality (display the current date, echo a random hash string) on your wordpress weblog: Go procedual.
If you are writing a tiny tool that does something you need to get done, if you are writing a tiny cron job batch script in PHP or if you are just fooling arround - do as you like.

But if you plan to develop sustainable, maintainable, testable, reusable, quality software that has a lot of features you should at least use OOP. Because it is bloody 2014.
OOP will enable you to blackbox and whitebox test units of your code seperately. It will enable you to not only efficiently reuse libraries and modules written by others but alos enable you to produce modules and libraris that can be reused by others.

Differences in procedural and object-oriented implementations of mysql in php?

The answer to which one is better is "it depends." As with anything, there are a variety of different approaches and you should also keep in mind that code that uses objects is not necessarily object oriented but can still be written procedurally. In the same vein, code that does not use objects can still be modular.

I would choose to use the mysqli class every time, though. There is no significant difference in performance. You probably won't realize some of the advantages of using a DB class such as simplified polymorphism, so my only argument for using the class is that I prefer the syntax. However, rather than use mysqli directly I would probably recommend that you extend or compose it. You can only do this with the class.

class DB extends mysqli {
public function __construct() {
parent::__construct($_SERVER['DB_HOST'],
$_SERVER['DB_USER'], $_SERVER['DB_PASS']);
}
}

This is a very shallow example.

An example of the polymorphism I was talking about above would be something like this:

class User implements DAO {
private $db;
public function __construct(DB $db) {
$this->db = $db;
}
}

//Testing code is simplified compared to using it in production
class TestDB extends DB {}
new User(new TestDB);
new User(new DB);

By the way I categorically prefer PDO over mysqli

Difference between calling a function by procedural or object oriented style

No, there is no difference. The procedural way is pretty much just a wrapper around the OO API. Historically it was included to allow developers for whom OO was a complete mystery to transition to a better alternative from the mysql API.

For all intents and purposes mysqli_num_rows does this:

function mysqli_num_rows(mysqli_result $result) {
return $result->num_rows;
}

Do object oriented PHP and procedural PHP do the same thing?

They are different approaches to the same problem.

However, for large projects you really don't want to go procedural. Mixing OO code with a good design pattern like MVC (Model-view-controller) is the way you want to go, as it is easier to maintain and expand. it also allows you to develop reusable classes and methods instead of rewriting the same thing over and over again - the DRY (Don't repeat yourself) principle. I tend to use this MVC framework for a lot of the smaller systems I write, and it's useful as an introduction to both OO and MVC.

Why is object oriented PHP with mysqli better than the procedural approach?

The main reason is that PHP is moving steadily in the direction of OO programming.

There's nothing wrong with using mysqli_xxx() functions rather than the OOP equivalents; it is exactly the same as far as the code is concerned.

The only issue is that you'll be getting yourself further and further behind the curve in terms of what people think of as well-written PHP code.

It's worth noting that the PDO library, which is considered the ideal for most DB code in PHP is OOP-only. It doesn't have a procedural interface. And nor do most of the other new features added to PHP in the last few versions. If you want to use PHP to its fullest, you need to know OOP anyway.

There's also the point about the ability to create an extension class for your DB -- something like this:

class myDB extends mysqli {
.... your own stuff here to extend and improve the base mysqli class
}

Of course you can achieve the same thing with procedural code, but it's not as neat as the OOP way. And of course that's only relevant if you actually want to extend the class.

However, as a first step, just moving from mysql_xxx() to mysqli_xxx() is a great start. Moving the whole way to using the OOP interface would be even better, but just switching to the mysqli functions is a good start.

Using the procedural interface to begin with will certainly make the transition away from the old mysql_xx() functions easier, so if switching to the OOP interface is too much of a leap at the beginning, don't feel you have to do it all in one go. Start with a conversion to the procedural mysqli functions, then switch to the OOP methods later on; neither jump will be that big on its own.

php procedural with namespace vs oop

You are thinking of OOP the wrong way. If you are trying to compare OOP with procedural namespaces merely as two different ways of organizing your code and function calls then certainly namespaces will seem more efficient.

The advantage of OOP isn't in organizing an object full of functions. That just treats OOP classes as big "utils" classes full of functions. The advantage of OOP isn't organizational. It is an entirely different way of building your programs that causes you to break your code into smaller, discreet entities. I use OOP in all of my PHP programs, even for small projects.

The advantage of OOP becomes most clear for me when doing any project that accesses a database (which is pretty well everything nowdays). I create small classes to model each database table and then access the information in these tables as objects. I have some base classes I use in all my projects that define how to map tables to objects so I don't retype or paste mysql commands any more. I just use the objects and they inherit all the needed functionality for inserting, updating and deleting from the database.

It sure is far more useful in code (especially if you use a PHP ide that has code completion) to see this in code:

echo "Hello, {$someDataObject->name}!";

Than this:

echo "Hello, " . $row['name'] . "!";

The difference might not be obvious right away. Both examples are a single line of code to print a table column. But the second example requires that I know the column names in my head. The first example has the column names embedded in the classes as properties. My code inspector knows all the properties so when I code it presents a list of all the properties as I type.

Maintaining the classes is easier than you think. Depending on the object framework you choose there are scripts to generate classes from tables and keep them up to date. And I find it FAR less error and bug prone to keep my object classes up to date myself than to have database changes break code because column names changed and then I have to update those column references in dozens of places. Yes, there is search and replace, but do you see the advantage of updating one file for your column change than updating every reference to $row['some_column']?

I hope this helps answer your question.

What is correct, Procedural Oriented Programming or Procedural Programming?

I'd say 'procedural programming' is correct and more common. However, since it's often contrasted with object-oriented programming, 'procedural-oriented programming' has become more common.

I'd say it's technically wrong though. First off, they're not opposed, you can have an object-oriented procedural language and do both. Secondly, a procedural language is procedural, not just 'procedure-oriented'. Similarly, some people call specific languages that are more object-oriented than others by design 'object-based'.

Another cause for confusion may be protocol-oriented programming (pop), which is an acronym that is sometimes (incorrectly) associated with procedural programming.

Wikipedia provides a good overview of the common programming paradigms and their correct names https://en.wikipedia.org/wiki/Comparison_of_programming_paradigms

OO or procedural PHP for website?

but it is important that the code is fairly easy to understand for a programmer with a decent amount of PHP experience.

Readability of code is not tied to a programming paradigm but to how the code is written. I have seen my fair share of spaghetti OOP (including my own) and I have seen an equal amount of procedural messes. If the code is well written, even someone without a decent amount of PHP knowledge should be able to follow along.

I'm guessing most PHP-programmers are not used to OO-code, so perhaps this is one point in favor of procedural code?

I doubt this. I've been to a number of conferences and no one there seemed to have any problems with OOP. In fact, I didnt even see a single line of procedural code. Also, all of the major frameworks are full OOP. You will find the procedural paradigm mainly in PHP4 applications and when looking at rookie code.

But to answer your question: I'd say use OO if that is what you and your developers are comfortable with. Personally, I find procedural code in the View part a bad idea, because you will likely end up intermingling logic and presentation code for completely unmaintainable templates. See the POEAA's Web Presentation Patterns for some more maintainable approaches.

You don't have to use MVC if you feel its too oversized. Use a Page Controller if you like. But then again, MVC aint that hard to implement either and there is plenty frameworks out there that will take the brunt of work away from you.

PHP Procedural combined with OOP

You will always have to have some "procedural code" in PHP. For instance, any plain algorithm you write inside a class method is going to be mostly procedural. Also, PHP has procedural entrance points only. Meaning, in Java for instance you have to create a class even to just get your application started. In PHP you will have to have at least one line of plain procedural code which instantiates an object before "OOP PHP" even begins.

So, yes, in practice you'll always mix the two. Use objects where appropriate and where they simplify code; don't force OOP on everything you possibly can even if it makes no sense.



Related Topics



Leave a reply



Submit