How do I check in PHP that I'm in a static context (or not)?

后端 未结 11 1311
时光说笑
时光说笑 2020-11-30 08:16

Is there any way I can check if a method is being called statically or on an instantiated object?

11条回答
  •  天涯浪人
    2020-11-30 09:05

    Create a static variable and change it in the constructor.

    private static $isInstance = false;
    
    public function __construct()
    {
        self::$isInstance = true;
    }
    

    Now you can check it

    public function myMethod()
    {
        if (self::$isInstance) {
            // do things
        }
    }
    

提交回复
热议问题