PHP: Interface type attribute

2

I am doing a study of Project Patterns. My first pattern is Strategy, where I have an abstract class that has two attributes that should instantiate a class that implements a given interface.

The interfaces:

interface FlyBehavior
{
    public function fly();
}

interface QuackBehavior
{
    public function quack();
}

The abstract class:

abstract class Duck
{
    protected $flyBehavior;
    protected $quackBehavior;

    abstract function display();

    protected function performFly()
    {
        return $this->flyBehavior->fly();
    }

    protected function performQuack()
    {
        return $this->quackBehavior->quack();
    }
}
The point is this: I have some classes that implement FlyBehavior and QuackBehavior, and it's these classes of this type that should be assigned to the $ flyBehavior and $ quackBehavior attributes and I'd like to declare it as follows:

abstract class Duck
{
    protected FlyBehavior $flyBehavior;
    protected QuackBehavior $quackBehavior;
}

However, if I do this, the publisher will acknowledge the error. How can I do it? This is wrong? I know that you can specify the type of variable in function parameters, I imagine it is also possible in attributes, as in languages like Java.

    
asked by anonymous 07.09.2017 / 17:53

1 answer

0

Yes, this is wrong. It does not make sense for you to set the type of an attribute in a dynamic typing language. This is only possible in static typing languages, such as Java, which was quoted.

What happens is that you have a business rule that must be applied whenever there is an attribute assignment ( redundancy? ), so you should implement this business rule in a setter . Since the attribute belongs to the Duck class, just implement the method in this class:

abstract class Duck
{
    protected $flyBehavior;
    protected $quackBehavior;

    public function setFlyBehavior(FlyBehavior $behavior) {
        $this->flyBehavior = $behavior;
    }

    public function setQuackBehavior(QuackBehavior $behavior) {
        $this->quackBehavior = $behavior;
    }
}

So, as the type of the parameter is defined in the method, whenever there is an attribute assignment, its type will be validated. Since such types are interfaces, it even makes sense to do this and is the only way - except to check the type in the body of the setter method using instaceof .

    
08.09.2017 / 15:32