这是我的代码:
class {
$property = "something";
public static function myfunc() {
return $this->property;
}
}
Run Code Online (Sandbox Code Playgroud)
但是 PHP 抛出了这个:
不在对象上下文中时使用 $this
我知道,问题出$this->在静态方法中,好的,我将其删除如下:
class {
$property = "something";
public static function myfunc() {
return self::property;
}
}
Run Code Online (Sandbox Code Playgroud)
但遗憾的是 PHP 抛出了这个:
未定义的类常量“属性”
如何访问其中的静态方法之外的属性?
一般来说,你不应该这样做。由于某种原因,静态方法无法访问实例字段。不过,您可以执行以下操作:
// define a static variable
private static $instance;
// somewhere in the constructor probably
self::$instance = $this;
// somewhere in your static method
self::$instance->methodToCall();
Run Code Online (Sandbox Code Playgroud)
请注意,它仅适用于您的类的单个实例,因为静态变量在所有实例(如果有)之间共享。
您还需要添加一堆验证(例如 $instance null?)并注意所有可能会给您带来麻烦的实现细节。
无论如何,我不推荐这种方法。需要您自担风险使用它。