是否可以判断父类中的方法是否由parent ::显式调用,而不是自动调用,因为子类不包含被调用的方法?
答案 0 :(得分:2)
示例1:
class Par
{
function printit($which = false)
{
// when you call this method, based on variable it tells how it was called
if ($which) {
echo "called with parent \n";
} else {
echo "called with this \n";
}
}
}
class Chi extends Par
{
function callParent()
{
parent::printit(TRUE);
}
function callFunction()
{
$this->printit(FALSE);
}
}
$chi = new Chi();
$chi->callParent();
$chi->callFunction();
示例2:
class Par
{
function printit()
{
// get all functions in child class
$child_methods = array_diff(get_class_methods("Chi") , get_class_methods("Par"));
// if the function there is in child class, probably it was called from there
if (in_array(__FUNCTION__, $child_methods)) {
echo "called with child \n";
} else {
echo "called with parent \n";
}
}
}
class Chi extends Par
{
function callParent()
{
parent::printit();
}
function callFunction()
{
$this->printit();
}
}
$chi = new Chi();
$chi->callParent();
$chi->callFunction();