PHP: Interface type attribute

Asked

Viewed 103 times

2

I’m doing a study of Project Standards. My first standard is Strategy, where I have an abstract class that has two attributes that should receive instances of a class that implements a certain 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 is these classes of this type that should be assigned to the $flyBehavior and $quackBehavior attributes and I would like to state it as follows:

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

But if I do this the editor accuses error. How can I do it? Is this wrong? Because I know that you can specify the type of variable in function parameters, I imagine it is also possible in attributes, as well as in languages like Java.

1 answer

0


Yes, this is wrong. It makes no sense for you to define the type of an attribute in a dynamic typing language. This is only possible in static typing languages, such as Java, which has been cited.

What happens is that you have a business rule that should be applied whenever there is an attribution to the attribute (redundancy?), then you should implement this business rule in a method Setter. Since the attribute belongs to the class Duck, 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;
    }
}

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.