Php物件導向?靜態成員

來源:互聯網
上載者:User
Php物件導向?靜態成員

靜態屬性

使用static關鍵字聲明的屬性

該靜態屬性,在邏輯上,是定義在類上面的屬性。保證一個類,對應一個屬性。

例子:

class Student

{

public $stu_id;

public $stu_name;

public static $stu_count = 0;

public function __constuct($id,$name)

{

$this->stu_id = $id;

$this->stu_name = $name;

}
}

訪問靜態屬性:

通過類來訪問:在利用靜態訪問符號(::)

類::成員

例子:

class Student

{

public $stu_id;

public $stu_name;

public static $stu_count = 0;

public function __constuct($id,$name)

{

$this->stu_id = $id;

$this->stu_name = $name;

Student::$stu_count ++;

}
}

::的訪問稱之為靜態訪問,->為非靜態訪問(對象訪問)

在訪問靜態屬性時,如果是在類內訪問:則可以使用self當前類

例子:

class Student

{

public $stu_id;

public $stu_name;

public static $stu_count = 0;

public function __constuct($id,$name)

{

$this->stu_id = $id;

$this->stu_name = $name;

self::$stu_count ++;

}
}

注意:$this 和 self 的區別

$this 表示的是這個對象,self表示這個類

靜態方法

靜態方法的邏輯意義,也是定義再類上的方法。同樣,調用形式類::

例子:

class Student

{

public $stu_id;

public $stu_name;

public static $stu_count = 0;

public function __constuct($id,$name)

{

$this->stu_id = $id;

$this->stu_name = $name;

self::$stu_count ++;

}

public static function sayCount()

{

echo “run static ”;

}
}

Student::sayCount();

靜態方法和非靜態方法,的主要區別,在於是否可以接收一個對象的執行環境。

就是是否可以為方法內的$this是否可以被賦值

只有在對象調用方法時,才能將對象執行環境傳遞到方法內,$this才可以被賦值。

靜態方法中無法使用非靜態屬性。

一個靜態方法,只能處理待用資料(靜態屬性)

例子:

class Student

{

public $stu_id;

public $stu_name;

public static $stu_count = 0;

public function __constuct($id,$name)

{

$this->stu_id = $id;

$this->stu_name = $name;

self::$stu_count ++;

}

public static function sayCount()

{

echo self::$stu_count;

}
}

Student::sayCount();

Php中特殊的方法訪問問題:

強調:靜態方法應該類來調用,非靜態方法應該對象來調用

class C

{

public function f1()

{

echo‘f1
’;

}

public static function f2()

{

echo‘f2
’;

}

}

$o = new C;

$o->f1();

C::f2();

但是:

1. 無論靜態還是非靜態方法,都可使用類訪問:不過如果類靜態調用一個非靜態方法,會報告一個文法不標準的錯誤。

2. 區別就在於$this上

只有再使用對象調用非靜態方法時,才可以使用方法內的$this.

class C

{

public function f1()

{

echo‘f1
’;

}

public static function f2()

{

echo‘f2
’;

}

}

C::f1();

C::f2();

總結:類的靜態方法和非靜態方法,類都只儲存一份,只是運行時的運行環境不同。只有再使用對象調用非靜態方法時,才可以使用方法內的$this.

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.