vendredi 9 janvier 2015

Override method to take argument from a derived subclass

I ended up a couple of times with a solution where i have two hierarchies of classes. Where classes from the first (Greeters) hiearchy uses classes from the second (Users).


Heres a ex:



class User {}
class Admin extends User {
function getSecretMessage() {
return "secret";
}
}

class Greeter {
public function hello(User $a) {
echo "hello!";
}
}

class AdminGreeter extends Greeter {
public function hello(Admin $a) {
parent::hello($a);
echo "in addition heres a secret of mine: " . $a->getSecretMessage();
}
}


Here i have User's and Greeter's, In PHP i receive the error (strict)


"Declaration of AdminGreeter::hello must be compatible with Greeter::hello"


I would like the AdminGreeter::hello to simply "extend" the Greeter::hello with data from a more specialized class (Admin).


What alternatives do i have to build something similar i PHP??


I guess the main problem is that PHP does not support "method overloading" and thereby if i were to send in a User instance to the AdminGreeter it would break. But if i had "method overloading", the Greeter::hello would simply be called if passed in a User instance.


It might be overall bad design, since i end up with this issue, maybe someone can point me to a better design for this problem.


As i side note i seem to have the same issue when developing Objective-C


Aucun commentaire:

Enregistrer un commentaire