5

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.

3 Answers 3

6

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.

1
  • can you give an example?
    – Sequoya
    Apr 26, 2016 at 17:22
2

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');
   }
}
1
  • Maybe, in Java we can create the X class like this: public abstract class X<T> { public abstract void method( T param ); } public abstract class Y<ClassName1> { public void method( ClassName1 param ) { ... }}
    – Sequoya
    Apr 26, 2016 at 14:53
1

I believe the unique way to go is this?

class A {}

class B extends A {}
class C extends A {}

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

class Y {
      public function method(B $param ) {}
}


class Z {
      public function method(C $param ) {}
}

$y = new Y();
$z = new Z();

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.