0

I have a question, can a method from an interface get additional parameters during the implementation like an abstract method? for example:

<?php

interface Figures {

    public function setColor($color);
}

class Circle implements Figures {

    public function setColor($color, $additional_parameter, ...) {

    }
}

?>

2

3 Answers 3

3

No, it will give you an error like this

Fatal error: Declaration of Circle::setColor() must be compatible with Figures::setColor($color)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer :)
2

You can do this as long as you make the additional parameters optional:

public function setColor($color, $additional_parameter = "defaultvalue", $another_parameter = null) { ...

Still it's not the best idea as it will be hard to use your code in a predictable way, as sometimes your argument will be just ignored. It's also bad practice not to follow the interface definition strictly.

1 Comment

Thank you for your answer, I didn't know that.
1

Re your question: no.

An interface is supposed to provide a "contract" that all children must adhere to. As such, it might not be a good idea to break that contract by doing extra things anyway.

An alternative option is to provide a public setter for the additional parameters, then access them by properties within setColor():

interface Figures {

    public function setColor($color);
}

class Circle implements Figures {
    protected $_additionalParameter;

    public function setColor($color) {
        echo $this->_additionalParameter . ' - not passed in any more';
    }

    public function setAdditionalParameter($blah = '')
    {
        $this->_additionalParameter = $blah;
        return $this;
    }
}

And used like so:

// you implement stuff
$circle = new Circle;
$circle->setAdditionalParameter('blah')
       ->setColor('color');
// blah - not passed in any more

If you have lots of additional parameters you might find it tidier to use the magic method __set() to cover all your bases instead of loading up your classes with lots of them.

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.