Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add classname type to the parameter of abstract method?

I have an abstract class with this method:

abstract class X {
   abstract public function method( $param );
}

In the implementation I do:

class Y extends X {
   public function method( ClassName1 $param )
   {
       ...
   }
}

class W extends X {
   public function method( ClassName2 $param )
   {
       ...
   }
}

I need to put the ClassName1 and the ClassName2 in both methods, but I get this error:

Declaration of Y::method() must be compatible with X::method($param) in ...

What I need to declare the abstract method in class X to solve the problem? The real question maybe: What be the class name in X::method( _____ $param ) to solve the problem?

Thanks.

like image 461
Sequoya Avatar asked Apr 26 '16 12:04

Sequoya


People also ask

Can abstract class be used as a parameter type?

The answer to this is: you cannot do it. This is a mathematical fact and has nothing to do with the programming language involved.

Can abstract method take parameters?

Yes, we can provide parameters to abstract method but it is must to provide same type of parameters to the implemented methods we wrote in the derived classes.

Can an abstract class have subclasses?

Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .

How do you declare an object of an abstract class?

We cannot create objects of an abstract class. To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass. A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.


2 Answers

You can create an interface. ClassName1 and ClassName2 implement that interface. Now you can use your interface as a type-hint in your method parameter. Based on your tag polymorphism, you may know how to use interfaces, what they are and what the benefits are. This approach is called Design by contract and is considered best practice.

like image 155
ST2OD Avatar answered Oct 13 '22 01:10

ST2OD


I don't think you're going to get away with doing this because you're type hinting two different classes. When you use an abstract or interface, it's basically a promise to implement a method in the same way the it's been previously defined. Your adding of the type hint makes them decidedly incompatible.

The best thing I can suggest is to do the check inside the method itself

class Y extends X {
   public function method( $param )
   {
       if(get_class($param) != 'ClassName1') throw new Exception('Expected class ClassName1');
   }
}
like image 29
Machavity Avatar answered Oct 13 '22 01:10

Machavity