dstk51319
2012-10-11 08:15
浏览 22
已采纳

在PHP中的扩展类中重新定义方法时返回正确的类名

I expected the first example code produces the result same as the second one but it didn't. So in order to get the correct class name, I have to redefine the custom msg() method in the extended class.

I'd like to know why the first one does not produce the extended class name and why it does when the method is redefined which is exactly the same.

Example 1

call_user_func(array(new MyClass_Mod, "msg"));

class MyClass {
    function msg() {
        echo '<p>get_class(): ' . get_class() . '</p>';
    }
}
class MyClass_Mod extends MyClass {
}

output

get_class(): MyClass

Example 2

call_user_func(array(new MyClass_Mod, "msg"));

class MyClass {
    function msg() {
        echo '<p>get_class(): ' . get_class() . '</p>';
    }
}
class MyClass_Mod extends MyClass {
    function msg() {
        echo '<p>get_class(): ' . get_class() . '</p>';
    }
}

output

get_class(): MyClass_Mod

I'd like to know the mechanism, so please do not suggest to use get_called_class(). I'm not able to use it for the version below PHP 5.3. Thanks for your input.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dongyongyu0789 2012-10-11 08:16
    最佳回答

    You just have to pass $this argument to get_class function.

    get_class($this);
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题