加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何使用parent :: method访问父类中的变量

发布时间:2020-12-13 17:15:22 所属栏目:PHP教程 来源:网络整理
导读:我在Parent Class.i中有受保护的变量UserId我将在我的子类中扩展变量,如下所示 class Main{ protected $UserId = "151"; protected static $UserName = "Madhavan"; protected function SampleMethod() { print "This is Sample Method"; } }class SubMain e
我在Parent Class.i中有受保护的变量UserId我将在我的子类中扩展变量,如下所示

class Main
{
  protected $UserId          = "151";
  protected static $UserName = "Madhavan";      

  protected function SampleMethod()
  {
    print "This is Sample Method";
  } 
}


class SubMain extends Main
{   
  function __construct()
  {    
    print parent::SampleMethod();

    print "User Id is ".$this->UserId."<br/>";          
    print parent::$UserName;
    print "User Id is ".parent::$UserId."<br/>";            
  }
}

当我使用$this-> UserId时打印正常.但是当我使用Parent :: $UserId时显示错误

致命错误:访问未声明的静态属性:Main :: $UserName

为什么它没有显示我通过parent :: SampleMethod()访问的函数,因为该函数不是静态的.

解决方法

这是因为函数是可覆盖的(因此同名的旧版本共存)而属性不是(声明只是相互覆盖,属性不应在后代类中重新声明).您始终使用$this->访问属性的唯一实例如果它不是静态的,那么self ::如果它是静态的. (如果在多个祖先类中声明了属性,仍然只存在一个数据字段,因此您不能引用任何“其他”或“之前的”.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读