Viewed   62 times

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?

 Answers

2

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.

Thursday, September 1, 2022
 
2

This is a correct implementation; you should use static, not self, in order to use late static bindings:

abstract class AbstractFoo{
    public static function foo() {
        throw new RuntimeException("Unimplemented");
    }
    public static function getFoo(){
        return static::foo();
    }
}

class ConcreteFoo extends AbstractFoo{
    public static function foo(){
        return "bar";
    }
}

echo ConcreteFoo::getFoo();

gives the expected "bar".

Note that this is not really polymorphism. The static keywork is just resolved into the class from which the static method was called. If you declare an abstract static method, you will receive a strict warning. PHP just copies all static methods from the parent (super) class if they do not exist in the child (sub) class.

Tuesday, December 20, 2022
 
c._s.
 
5

PHP will support closures natively in 5.3. A closure is good when you want a local function that's only used for some small, specific purpose. The RFC for closures give a good example:

function replace_spaces ($text) {
    $replacement = function ($matches) {
        return str_replace ($matches[1], ' ', ' ').' ';
    };
    return preg_replace_callback ('/( +) /', $replacement, $text);
}

This lets you define the replacement function locally inside replace_spaces(), so that it's not:
1) Cluttering up the global namespace
2) Making people three years down the line wonder why there's a function defined globally that's only used inside one other function

It keeps things organized. Notice how the function itself has no name, it simply is defined and assigned as a reference to $replacement.

But remember, you have to wait for PHP 5.3 :)

You can also access variables outside it's scope into a closure using the keyword use. Consider this example.

// Set a multiplier  
 $multiplier = 3;

// Create a list of numbers  
 $numbers = array(1,2,3,4);

// Use array_walk to iterate  
 // through the list and multiply  
 array_walk($numbers, function($number) use($multiplier){  
 echo $number * $multiplier;  
 }); 

An excellent explanation is given here What are php lambdas and closures

Monday, September 26, 2022
 
xanthir
 
1

do it

public $numrows;
public function fetchDataByEmail($email) {
        $result=mysql_query(" SELECT * FROM users WHERE email='$email'"); 
        while($row = mysql_fetch_assoc($result)) {
        $fetch[] = $row;
        }
        $this->numrows = mysql_num_rows($result);  
        return $fetch;  
}

then

$info = new userinfo();
$detail = $info->fetchDataByEmail('[email protected]');  
print_r($detail); // return all result array
$info->numrows; // will return number of rows.
Tuesday, November 15, 2022
4

Either use Interfaces and implement the methods manually or via Strategies. Or use Composition instead of Inheritance, meaning you let the Order_Product have a Order_Item and a Cart_Product.

On a sidenote: You could also consider making "shipping calculations" into it's own Service class that you can pass appropriate Product instances to.

Monday, December 12, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :