duanoucuo7045 2015-02-23 15:30
浏览 13

PHP:在静态调用方法中调用时,真的会混淆$ this“小故障”

This is one of those "my code works, I don't know why" times.

I have a method in an instantiated class that statically calls a method of what is basically a static class. I say "basically" because while coding it I neglected to declare the methods of the class exclusively static. The method in question belongs to the first class but I blindly copy/pasted the code (which was originally internal) and didn't quite update everything, so the $this-> remained even though the method doesn't belong to the class it's within.

So, basically I had this:

class MyClass{
    public function callOtherMethod(){
        OtherClass::otherMethod();
    }
    public function myMethod(){
        echo 'Tada!';
    }
}

class OtherClass{
    public function otherMethod(){
        echo get_class($this);
        $this->myMethod();
    }
}

$thing = new MyClass();
$thing->callOtherMethod();

This somehow worked without issue until I did some cleanup and explicitly declared the OtherClass' methods static as they were meant to be. Everything worked because, for some reason I was unaware of, $this while used within OtherClass instead references the instantiated object that called it (i.e. MyClass).

I didn't think this should be possible, should it? I know it's bad coding standards and I'm making revisions to avoid it, but I found it really, really weird.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 matlab不知道怎么改,求解答!!
    • ¥15 永磁直线电机的电流环pi调不出来
    • ¥15 用stata实现聚类的代码
    • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
    • ¥20 docker里部署springboot项目,访问不到扬声器
    • ¥15 netty整合springboot之后自动重连失效
    • ¥15 悬赏!微信开发者工具报错,求帮改
    • ¥20 wireshark抓不到vlan
    • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
    • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持