doufangmu9087 2015-01-24 23:25
浏览 128
已采纳

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

I have a class (yii2 widget) that has private properties and public static functions. When I try to access a private property from the static method like $this->MyPrivateVar an error is generated regarding that I don't have to use $this in non object context! The following is a snippet of my code:

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

I tried the following, but it seems that undergoes to infinite loop Maximum execution time of 50 seconds exceeded!

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

So how could I access the private juiThemeSelectId from the static method?

  • 写回答

2条回答 默认 最新

  • dongshang5862 2015-01-24 23:41
    关注

    The sort answer is: You can't access a non-static property in a static method. You don't have access to $this in a static method.

    What you could do is just to change the property to static like:

    private static $juiThemeSelectId = 'AASDD5';
    

    And then access it with this:

    echo self::$juiThemeSelectId;
    

    For more information about the keyword static see the manual: http://php.net/manual/en/language.oop5.static.php

    And a quote from there:

    Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里