Ben*_*ner 57
请尝试以下方法:
class Foo {
function bar() {
$static = !(isset($this) && get_class($this) == __CLASS__);
}
}
Run Code Online (Sandbox Code Playgroud)
来源:seancoates.com通过谷歌
小智 11
"将它从debug_backtrace()中删除"并不算太多.debug_backtrace()有一个'type'成员,如果一个调用是静态的,那么是'::',如果不是,则是' - >'.所以:
class MyClass {
public function doStuff() {
if (self::_isStatic()) {
// Do it in static context
} else {
// Do it in object context
}
}
// This method needs to be declared static because it may be called
// in static context.
private static function _isStatic() {
$backtrace = debug_backtrace();
// The 0th call is to _isStatic(), so we need to check the next
// call down the stack.
return $backtrace[1]['type'] == '::';
}
}
检查是否$this
已设置将不起作用.
如果从对象内调用静态方法,$this
则将其设置为调用者上下文.如果你真的想要这些信息,我想你必须把它挖出来debug_backtrace
.但是你为什么要首先需要呢?您有可能以某种方式更改代码的结构,以便您不这样做.
小智 6
我实际上在我的所有脚本上使用这行代码,它运行良好,它可以防止错误.
class B{
private $a=1;
private static $static=2;
function semi_static_function(){//remember,don't declare it static
if(isset($this) && $this instanceof B)
return $this->a;
else
return self::$static;
}
}
Run Code Online (Sandbox Code Playgroud)
使用instanceof不是偏执狂:
如果A类调用类B静态函数$this
可能存在于A范围内; 我知道这很乱,但php会这样做.
instanceof
将解决这个问题,并避免与可能实现"半静态"功能的类冲突.