Why Use PHP Oop Over Basic Functions and When

Why use PHP OOP over basic functions and when?

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.

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

When to use OOP with PHP?

When to use OOP with PHP?

Whenever you like, it's not a way of programming you must apply to when you use PHP. Use the language as a tool.

Related: What are the benefits of OO programming? Will it help me write better code?

I would prefer to work with objects now. P.S: I'm still a student.

If you want to work with objects with your current background, you might want to learn about OOAD as well. That's sort of a subjective comment, it helped me to better understand what object oriented programming is about.

Why should I use classes rather than just a collection of functions?

It's a way to view your code in a more intuitive, real-world way. (You package the data and all possible operations on that data together.) It also encourages encapsulation, abstraction, data hiding... What you're really looking for is the advantages of OOP.

Is OOP worth using in PHP?

Yes, it is almost always a good idea to use OOP. This is because OOP is a style of coding, and coding styles for the most part are easily able to be transferred accross languages.

People don't use coding-styles because they use a certain language. People use coding styles because the style of coding offers good methods to do things they feel are desirable. Therefore, as long as the basic elements are there (inheritance, class properties, etc), it will always be viable to write in that coding style.

No, using procedural functions to access them probably isn't a good idea. This is because, you probably will have to do something like this to maintain the state.

function myFunc()
{
global $class;
$class->doMethod();
}

function myFunc2()
{
global $class;
$class->doMethod2();
}

This is a bad idea as it creates a ton of global state.

PHP vs OO PHP - Which one to use?

The real advantage of object-orientation: your code is better organized, easier to maintain, more modular (and thus easier to reuse), and potentially less brittle (because of encapsulation of state and implementation, and hopefully better security). (The cynic in me also says that if you learn object-oriented PHP, you take the first important step to leaving the PHP ghetto. Heh. Worked for me!)

There's already a lot of questions from PHPers moving into OO on Stack Overflow:

  • PHP Object Oriented or Not?
  • Is my PHP code object oriented?
  • Learning PHP Class

Not to mention that there are zillions of PHP object-oriented tutorials out there. My take: basically, yes, if you are writing PHP, you should probably be writing object-oriented PHP for anything beyond the most trivial of applications. There are lots of Rails-like frameworks for PHP that will make your life easier, and may help you become a better programmer.

What's the difference between using normal functions and class methods in PHP?

OOP provides, among other things, encapsulation.

class Shop {

function __construct($items) {
$this->inventory = $items;
}

function deleteItem($item) {
$key = array_search($item, $this->inventory);
if ($key !== false)
unset($this->inventory[$key]);
}

}

Now you can create instances:

$computerShop  = new Shop(array('ram', 'monitor', 'cpu', 'water'));
$hardwareStore = new Shop(array('hammer', 'screwdriver', 'water'));

And each one of them is independent from each other. If I do $computerShop->removeItem('water'), $hardwareStore should still have water in their inventory. (see it in action) Doing this the procedural way is much messier.


Another cool thing about OOP is that you can use inheritance and polymorphism:

class Animal {

function eat() {
$this->hungry = false;
}

abstract function speak();
}

class Cat extends Animal {

function speak() {
echo 'meow!';
}
}

class Dog extends Animal {

function speak() {
echo 'woof!';
}
}

Now both Cat and Dogs can call the method eat() even though they are not explicitly declared in their classes - it's been inherited from their parent class Animal. They also have a speak() method that does different things. Pretty neat, huh?

Wikipedia:

Object-oriented programming, Encapsulation, Inheritance, Polymorphism

Functions vs OOP question

The appropriate metric is usefulness.

If this code does just one thing, accepts a few input parameters, and returns a single result, then it's a function.

If the code can collect data, and does something tricky on this data, and you can specifically reuse results or get different results, then turn it into an object.



Related Topics



Leave a reply



Submit