获取SubClass实例

时间:2013-04-26 03:16:28

标签: php class inheritance instance

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

On 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

1 个答案:

答案 0 :(得分: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

P.S。:为什么不在每个类中覆盖方法?