如何检查调用某个方法的子类,以确定该方法将如何执行?
在Classes.php上:
class Generic {
public function foo() {
// if its being called by Specific_1 subclass
echo "bar";
// if its being called by Specific_2 subclass
echo "zoo";
}
}
class Specific_1 extends Generic {}
class Specific_2 extends Generic {}在脚本上:
$spec1 = new Specific_1();
$spec2 = new Specific_2();
spec1->foo() // pretend to echo bar
spec2->foo() // pretend to echo zoo发布于 2013-04-26 11:23:10
尝试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附言:为什么不直接覆盖每个类中的方法呢?
https://stackoverflow.com/questions/16228168
复制相似问题