How to add classname type to the parameter of abstract method?
Asked Answered
E

3

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.

Enlistee answered 26/4, 2016 at 12:14 Comment(0)
H
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.

Homogeneity answered 26/4, 2016 at 12:21 Comment(1)
can you give an example?Enlistee
S
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');
   }
}
Shirleneshirley answered 26/4, 2016 at 12:21 Comment(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 ) { ... }}Enlistee
E
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();

?>
Enlistee answered 26/4, 2016 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.