user838531
user838531

Reputation: 488

passing interface as function parameter (PHP)?

I am watching one of Jeffs Laracast Tutorials about coding rules.

function signUp($subscription) 
{
    if ($subscription == 'monthly')
    {
        $this->createMonthlySubscription();
    }
    elseif ($subscription == 'forever')
    {
        $this->createForeverSubscription();
    }
 }

He wants to use polymorphism and interfaces here. He changes the above code to:

function signUp(Subscription $subscription)
{
    $subscription->create();
}

I don't understand what he is doing here. Is he passing the interface "Subscription" as a function parameter..? I never saw this in all previous tutorials about interfaces.

Upvotes: 6

Views: 6967

Answers (2)

shafeeque ahmad
shafeeque ahmad

Reputation: 97

here is the detail explanation according to your given case I hope so after that you will understand this concept properly


Interface Subscription{
    public function create();
}

class MonthlySubscription implements Subscription{

    public function create(){
        print_r("this is monthly subscription create method");
    }

}

class ForeverSubscription implements Subscription{

public function create(){
        print_r("this is yearly subscription create method");
    }   

}


class user {

public function signUp(Subscription $subscription){

    $subscription->create();

}

public function getSubcriptionType($type){

if($type=='forever'){

    return new ForeverSubscription;

}

    return new MonthlySubscription;

}


}

$user=new User();

$subscription=$user->getSubcriptionType('forever');

$user->signUP($subscription);


public function signUp(Subscription $subscription){
    $subscription->create();
}

In this method you are trying to do method injection
method injection means passing a dependency(instance/refference/object etc) into a method

in Singup(Subscription $subscription) mentod


Subscription is a 'type hint'
which ensure that object that will be pass to signUp() function must be an instance of that class who implemented 'Subscription ' interface

Upvotes: 3

Polygnome
Polygnome

Reputation: 7795

function signUp(Subscription $subscription)
{
    $subscription->create();
}

This methods expects a single paramater called $subscription. This paramater has to be a concrete object (or null) that implements the Subscription interface.

This is done via a so called "type hint" (http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration) before the parameter.

Subscription does not need to be an interface here - it could also be a class, and the given parameter must either be an instance of Subscription or any derived type.

Upvotes: 12

Related Questions