尝试instanceof
关键字:
<?php
header('Content-Type: text/plain');
class Generic {
public function foo() {
if($this instanceof Specific_1)echo "bar";
if($this instanceof Specific_2)echo "zoo";
}
}
class Specific_1 extends Generic {}
class Specific_2 extends Generic {}
$a = new Specific_1();
$a->foo();
echo PHP_EOL;
$b = new Specific_2();
$b->foo();
?>
显示:
bar
zoo
试用is_a()
功能:
<?php
header('Content-Type: text/plain');
class Generic {
public function foo() {
if(is_a($this, 'Specific_1'))echo "bar";
if(is_a($this, 'Specific_2'))echo "baz";
}
}
class Specific_1 extends Generic {}
class Specific_2 extends Generic {}
$a = new Specific_1();
$a->foo();
echo PHP_EOL;
$b = new Specific_2();
$b->foo();
?>
显示:
bar
baz
另一种方式get_called_class()
:
<?php
header('Content-Type: text/plain');
class Generic {
public function foo() {
switch($class = get_called_class()){
case 'Specific_1':
echo "bar";
break;
case 'Specific_2':
echo "zoo";
break;
default:
// default behaviour...
}
}
}
class Specific_1 extends Generic {}
class Specific_2 extends Generic {}
$a = new Specific_1();
$a->foo();
echo PHP_EOL;
$b = new Specific_2();
$b->foo();
?>
显示:
bar
zoo
PS:你为什么不只是覆盖每个类中的方法?