2013-04-26 75 views
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 

回答

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