2010-12-22 98 views
0

我想要一个具有基本属性和函数的基类,所以我不必在所有子类中定义它们。
我使用php 5.3.3。在父类中获取子类的函数名称

这是不可能的吗?

class A { 
    private $debug; 
    private $var; 
    protected function setVar($str) { 
    $this->debug = 'Set by function `'. MAGIC_HERE .'` in class `'. get_called_class() .'`.'; 
    $this->var = $str; 
    return true; 
    } 
    protected function getVar() { 
    return $this->var; 
    } 
    protected function getDebug() { 
    return $this->debug; 
    } 
} 
class B extends A { 
    public function __construct() { 
    $this->doSomething(); 
    } 
    public function doSomething() { 
    $this->setVar('my string'); 
    } 
} 
$myobj = new B(); 
$myobj->getDebug(); 
// expected output "Set by function `doSomething` in class `B`." 
+0

可能的重复:http://stackoverflow.com/questions/190421/caller-function-in-php-5 – 2010-12-22 16:27:45

回答

0
<?php 
class A { 
    private $debug; 
    private $var; 
    protected function setVar($str) { 
    $this->debug = 'Set by function `'. MAGIC_HERE .'` in class `'. get_called_class() .'`.'; 
    $this->var = $str; 
    return true; 
    } 
    protected function getVar() { 
    return $this->var; 
    } 

    // Notice the public here, instead of protected // 
    public function getDebug() { 
    return $this->debug; 
    } 
} 
class B extends A { 
    public function __construct() { 
    $this->doSomething(); 
    } 
    public function doSomething() { 
    $this->setVar('my string'); 
    } 
} 
$myobj = new B(); 
echo $myobj->getDebug(); 
// expected output "Set by function `doSomething` in class `B`." 

您刚刚两个小问题。 A::getDebug需要公开才能从外部访问,并且您忘记输出A::getDebug的回报。

0

查看debug_backtrace函数。请注意,此功能非常昂贵,因此您应该禁用生产中的这些调试功能。

0

这不适合你吗?

我没有在本地运行5.3,所以我不得不切换get_called_class(),但仍然可以使用它。应该明确表示,对不起。

class A { 
    private $debug; 
    private $var; 
    protected function setVar($str, $class) { 
    $this->debug = 'Set by function `` in class `'. $class .'`.'; 
    $this->var = $str; 
    return true; 
    } 
    protected function getVar() { 
    return $this->var; 
    } 
    public function getDebug() { 
    return $this->debug; 
    } 
} 
class B extends A { 
    public function __construct() { 
    $this->doSomething(); 
    } 
    public function doSomething() { 
    $this->setVar('my string', __CLASS__); 
    } 
} 
$myobj = new B(); 
echo $myobj->getDebug();