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

Sai*_*akR 4 php oop

我有一个类(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;
    ...
  }
Run Code Online (Sandbox Code Playgroud)

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

public static function createSelectList($items)
  {
    $t = new JuiThemeSelectWidget;
    $juiThemeSelectId = $t->juiThemeSelectId;
    ...
  }
Run Code Online (Sandbox Code Playgroud)

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

Riz*_*123 5

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

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

private static $juiThemeSelectId = 'AASDD5';
Run Code Online (Sandbox Code Playgroud)

然后使用以下命令访问它:

echo self::$juiThemeSelectId;
Run Code Online (Sandbox Code Playgroud)

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

以及那里的引用:

由于静态方法无需创建对象实例即可调用,因此伪变量 $this 在声明为静态的方法内不可用。