1

I was wondering if it is possible to use interface parameters in PHP functions / methods.

I'm used to coding in .Net and using .Net this is possible, such as having the following interface:

interface IVehicleDataProvider
{
    public void Create(IVehicle Vehicle);
}

Then I could implement this in a class as such:

class CarDataProvider : IVehicleDataProvider
{
    public void Create(Car Car)
    {
        //do something
    }
}

or

class TruckDataProvider : IVehicleDataProvider
{
    public void Create(Truck Truck)
    {
        //do something
    }
}

as long as Car or Truck implements an IVehicle interface.

Can the same thing be done in PHP?

0

3 Answers 3

3

No, you can't define one type in the interface, and a different one (even though it's a subclass) in the implementor, the implementor must follow the interface completely.

But even if you define

function create(IVehicle $vehicle);

You can still pass in Cars and Trucks.

Sign up to request clarification or add additional context in comments.

2 Comments

So I would define function create(IVehicle $vehicle); in the class and then when calling this function I could pass in a different type such as VehicleDataProvider->Create(Car $car);?
Exactly. This will only work, of course, assuming Car is extending IVehicle.
0

No it will not work becouse the declaration in the class must be fully compatible with the interface declaration so you have to use IVehicle as parameter type.

Comments

0

Yes, you can use interfaces in PHP 5, although they are still relatively immature. For the example above, you would use something like the following:

interface IVehicleDataProvider
{
    public function create(IVehicle $vehicle);
}

class CarDataProvider implements IVehicleDataProvider
{
    public function create(IVehicle $car) {
        //do something
    }
}

PHP does not support return type declaration, so you cannot declare a function void (although you should make note of the return type in the function documentation).

You also cannot extend an interface, so if you declare that the create function in the IVehicleDataProvider interface accepts an instance of IVehicle, then the CarDataProvider::create, function must accept an instance of the IVehicle interface.

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.