- in_array: documentation ( source)
<?php
class Human {
public function speak() {
return "I can speak";
}
public function walk() {
return "I can walk";
}
public function jump() {
return "I can jump";
}
}
/* calling parent is working but lots of duplication */
/*
class Man extends Human {
// can speak and walk but overrides some of the human function
public function walk() {
return parent::walk() . " fast";
}
public function speak() {
return parent::speak() . " fast";
}
}
*/
class Man {
// can speak and walk but overrides some of the human function
public function __construct(Human $human) {
$this->_human = $human;
$this->_override = ["walk", "speak"];
}
private function _method($parentResult) {
return static::class . ": ". $parentResult . " fast";
}
public function __call($name, $arguments) {
return in_array($name, $this->_override) ?
$this->_method($this->_human->$name()) :
$this->_human->$name(); // here we could check if method exists
}
}
// woman is an example for static access to instance methods of parent --> could be also static at parent (just easier to test with the code here)
class Woman {
private static function _method($parentResult) {
return static::class . ": ". $parentResult . " fast";
}
public function __callStatic($name, $arguments) {
$_override = ["walk", "speak"];
$_human = new Human();
return in_array($name, $_override) ?
self::_method($_human->$name()) :
$_human->$name(); // here we could check if method exists
}
}
$human = new Human();
echo $human->speak() . "\r\n";
echo $human->walk();
echo "\r\n";
$man = new Man(new Human());
echo $man->speak() . "\r\n";
echo $man->walk() . "\r\n";
echo $man->jump();
echo "\r\n";
$woman = new Woman();
echo $woman::speak() . "\r\n";
echo $woman::walk() . "\r\n";
echo $woman::jump();