如何在 PHP 中从公共静态方法访问私有类的属性


How to access private class's property from public static method in PHP

我有一个类(yii2 widget),它具有私有属性和公共静态函数。当我尝试从静态方法访问私有属性时,例如$this->MyPrivateVar生成一个错误,说明我不必在非对象上下文中使用$this!以下是我的代码片段:

class JuiThemeSelectWidget extends Widget
{
  private $list;
  private $script;
  private $juiThemeSelectId = 'AASDD5';
  public $label;
  ....
 public static function createSelectList($items)
  {
    $t = $this->juiThemeSelectId;
    ...
  }

我尝试了以下内容,但似乎经历了无限循环Maximum execution time of 50 seconds exceeded

public static function createSelectList($items)
  {
    $t = new JuiThemeSelectWidget;
    $juiThemeSelectId = $t->juiThemeSelectId;
    ...
  }

那么如何从静态方法访问私有juiThemeSelectId呢?

排序答案是:不能在静态方法中访问非静态属性。您无权访问静态方法中的$this

您可以做的只是将属性更改为静态,例如:

private static $juiThemeSelectId = 'AASDD5';

然后用这个访问它:

echo self::$juiThemeSelectId;

有关关键字static的详细信息,请参阅手册:http://php.net/manual/en/language.oop5.static.php

还有一句话:

由于静态方法在没有所创建对象的实例的情况下是可调用的,因此伪变量$this在声明为 static 的方法中不可用。

您可以使用

self访问它:

public static function createSelectList($items)
{
  $t = self::juiThemeSelectId;
  ...
}