Search code examples
phpabstract-class

PHP abstract method with unknown number of arguments


I have:

  • abstract class Car with an abstract method called drive().

I have two classes which extend Car :

  1. Manual_Car
  2. Automatic_car

My problem is the method drive() has different number of arguments in this two cases.

This is the code :

abstract class Car{
    abstract public function drive( //variable number of args );
}

class Manual_Car extends Car{
   public function drive( $speed, $gearbox){
      ...
   }
}

class Automatic_Car extends Car{
   public function drive( $speed ){
      ...
   }
}

How can I declare my abstract class with an unknown number of arguments?


Solution

  • I found the solution ! Thanks to @Alex Howansky.

    Try to declare abstract class with unknown number of arguments is not the best practice because it makes a case of signature violation.

    Best Practice

    All extra argument like $gearbox should be a class parameter.

    Solution code in my example :

    abstract class Car{
    
        protected $arg1, $arg2;
    
        public function __construct( $arg1, $arg2 ){
             $this->arg1 = $arg1;
             $this->arg2 = $arg2;
        }
        abstract public function drive( $speed );
    }
    
    class Manual_Car extends Car{
    
       protected $gearbox;
    
       public function __construct( $arg1, $arg2, $gearbox ){
             parent::__construct( $arg1, $arg2 );
             $this->gearbox = $gearbox;
        }
    
       public function drive( $speed ){
          ...
          //use $this->gearbox here 
       }
    }
    
    class Automatic_Car extends Car{
       public function drive( $speed ){
          ...
       }
    }