2

Is there an oppotunity to create an interface function in PHP, where a parameter requires to be an object, but not specified, what object it has to be?

Now my code looks like this:

interface Container {
    public static function add(\Employee $element);
}

Right now I can just implement the function with a parameter, which requires an instance from "Employee". When I now implement it in a class it looks like this:

class EmployeeContainer implements Container {
    public static function add(\Employee $element) {
        $pnr = $element->getPNR();
    }
}

When I create another class, that implements Container and set the required Object for example to Trainee, the PHP compiler throws an error:

class TraineeContainer implements Container {
    public static function add(\Trainee $element) {
        $pnr = $element->getPNR();
    }
}

Fatal error: Declaration of TraineeContainer::add($element) must be compatible with Container::add(Employee $element)

Is there a way to set in the interface the required object to a custom object?

Why I want this?

Many IDE's supporting this form of instance description to suggest methods based on an object.

3
  • you can use same base class for Trainee and Employee and then use that class as argument in interface Commented Mar 28, 2017 at 9:13
  • @ChetanAmeta Can you show an example, I can't imagine it. Commented Mar 28, 2017 at 9:16
  • take a look at example in answer Commented Mar 28, 2017 at 9:26

2 Answers 2

2

Unfortunately not. Only way is you should check argument type inside your method:

public static function add($element) {
    if(!$element instanceof \Trainee) {
        throw new \InvalidArgumentException("your exception message");
    }

    $pnr = $element->getPNR();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Custome object argument is not possible in interface but you can achieve it in other way.

create a common base class

class SomeBaseClass{

}

extend your classes

class Employee extends SomeBaseClass{

}

class Trainee extends SomeBaseClass{

}

then use SomeBaseClass as argument in your interface

interface Container {
    public static function add(SomeBaseClass $element);
}

class EmployeeContainer implements Container {
    public static function add(SomeBaseClass $element) {
        $pnr = $element->getPNR();
    }
}

class TraineeContainer implements Container {
    public static function add(SomeBaseClass $element) {
        $pnr = $element->getPNR();
    }
}

It seems you have getPNR common function so you can create an abstract class or interface and use that in your child classes.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.