0

如何检查调用方法的子类以确定该方法将如何执行?

在 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
4

1 回答 1

0

尝试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:你为什么不只是覆盖每个类中的方法?

于 2013-04-26T03:23:09.947 回答