【问题标题】:How to access class property in method如何在方法中访问类属性
【发布时间】:2015-04-25 04:48:44
【问题描述】:

我有以下代码:

class FanClub_Banner
{
    public $img = 'http://www.example.com/museum/images/logo_ver_250.png';

    public static function banner_me(array $widget, $positionCode, array $params, XenForo_Template_Abstract $renderTemplateObject)
    {
        return '<img src="'. $this->$img . '" width="250" height="250" alt="Museum">';
    }
}

我得到了错误:

Fatal error: Using $this when not in object context in C:\public_html\comunidad\library\FanClub\Banner.php on line 8

如何解决?

谢谢

【问题讨论】:

    标签: php class methods properties


    【解决方案1】:

    您的静态方法无法访问您的 Class 属性,一个简单的解决方法是从 public static function 中删除 static 并在您想要使用此方法的地方使用 FanClub_Banner fcBanner = new FanClub_Banner(); fcBanner->banner_me(....);

    另一个解决方法是将属性也设为静态,这样您就可以拥有public static $img...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 2011-07-27
      • 2014-06-20
      • 2021-11-16
      • 1970-01-01
      相关资源
      最近更新 更多