【问题标题】:How can I tell if a function is being called statically in PHP? [duplicate]如何判断一个函数是否在 PHP 中被静态调用? [复制]
【发布时间】:2010-09-29 17:14:41
【问题描述】:

可能重复:
How to tell whether I’m static or an object?

假设我有一个 FooClass 和一个 bar() 方法。在bar() 方法内部,有没有办法判断它是否被静态调用,所以我可以区别对待这两种情况?

FooClass::bar();
$baz = new FooClass();
$baz->bar();

【问题讨论】:

  • 如果你想拥有一个静态和非静态的方法,你可能应该考虑重新设计类......你为什么要这样做?
  • 开启E_STRICT错误报告,让php在你做错时尖叫

标签: php oop


【解决方案1】:
class FooClass {

    function bar() {
        if ( isset( $this ) && get_class($this) == __CLASS__ ) {
            echo "not static";
        }
        else {
            echo "static";
        }
    }

}

FooClass::bar();
$baz = new FooClass();
$baz->bar();

【讨论】:

  • 就是这样,但将$this 包裹在isset() 中,不会触发任何额外的通知
  • 这仅适用于全局范围。如果你从另一个类调用它,$this 将被设置,而不是你想要的对象。可能想试试isset($this) && get_class($this) == __CLASS__
  • 如果 FooClass 被一个新类继承,这会起作用吗? CLASS 提供了它被声明的文件的类名,所以这将是 FooClass 并且可能不是继承 FooClass 的 InheritedFooClass?
猜你喜欢
  • 1970-01-01
  • 2015-03-18
  • 1970-01-01
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 2019-09-14
  • 2015-07-18
相关资源
最近更新 更多