1. 程式人生 > 實用技巧 >一張圖輕鬆記住PHP的類以及private和protected的區別

一張圖輕鬆記住PHP的類以及private和protected的區別

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

上圖概要的說了下PHP類的特性,類的方法同屬性類似。

圖中B類繼承自A類,B是A的子類,$x和$y都是B的例項化物件。

1. 原型引用:【A:: 、 B:: 】,僅限public static 屬性和方法

2. 例項引用:【$x-> 、$y-> 】,僅限public 屬性和public方法以及public static 方法

3. 關於 self:: 和 parent:: (類引用)

  self:: 當前方法所屬的類

  parent:: 父類

  如果self::後面的屬性或者方法未在當前類中定義,會嘗試用parent::替代self::

  self:: 和 parent:: 後面只能跟方法名或靜態屬性

4. 關於 $this (物件引用)

  $x->f() 中的 $this 是$x。

  $y->f() 中的 $this 是$y。

  $this-> 後面可以是動態屬性以及動態或靜態方法。

5. 關於 static::

  static:: 引用當前使用的類,類似 $this,但可以在未例項化的類中使用,在已例項化物件中可以理解成等同於$this

6. 關於static

  static標識的屬性只能通過 self:: 、parent::、static:: 、類名:: 靜態引用,不能通過 $this-> 物件引用

6. 關於 public 、protected 、private

  public : 可以在任何地方引用

  protected : 只能在類中引用,$this-> 、parent::

  private : 只能在本類中引用, $this->、self::

轉載於:https://my.oschina.net/feanlau/blog/994623