Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong Static Method

Tags:

php

static

PHP calls private method in parent class instead of method define in current class called by call_user_func

class Car {
    public function run() {
        return call_user_func(array('Toyota','getName')); // should call toyota
    }
    private static function getName() {
        return 'Car';
    }
}

class Toyota extends Car {
    public static function getName() {
        return 'Toyota';
    }
}

$car = new Car();
echo $car->run(); //Car instead of Toyota

$toyota = new Toyota();
echo $toyota->run(); //Car instead of Toyota
like image 683
Baba Avatar asked Dec 21 '12 08:12

Baba


People also ask

Why are static methods bad?

Static methods are bad for testability.Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.

Why should we avoid static methods in Java?

That's because static methods can't access the object's attributes. Static methods aren't part of the object, so they don't have access to anything that belongs to the object.

What is static abuse?

you are abusing static, if you are trying to do OOP and instead are making it reference programming by never having to create a new object and instead just need to call the class without ever making an instance. – jgr208. May 18, 2015 at 15:16.

Why are static methods good?

Not Changing State. Since static methods cannot reference instance member variables, they are a good choice for methods that don't require any object state manipulation.


2 Answers

I have found a solution with a different approach..

<?php
 class Car {
    public static function run() {
     return static::getName();
   }
   private static function getName() {
    return 'Car';
    }
  }

   class Toyota extends Car {
     public static function getName() {
        return 'Toyota';
      }
   }
echo Car::run();
echo Toyota::run();
  ?>

Using Late Static Binding..

like image 189
Mrinmoy Ghoshal Avatar answered Oct 07 '22 22:10

Mrinmoy Ghoshal


You might use something like this:

<?php

class Car {
    public function run() {
        return static::getName();
    }

    private static function getName(){
        return 'Car';
    }
}

class Toyota extends Car {
    public static function getName(){
        return 'Toyota';
    }
}

$car = new Car();
echo $car->run();

echo PHP_EOL;

$toyota = new Toyota();
echo $toyota->run();

?>

Output:

Car
Toyota

PHP 5.4.5

like image 3
BlitZ Avatar answered Oct 07 '22 21:10

BlitZ