php基礎知識:類與對象(5) static

來源:互聯網
上載者:User

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).
聲明靜態類變數和方法可以不需要執行個體化類對象的情況下對他們進行調用。靜態類不能被類對象調用。(類的靜態方法可以)。//注意看第一個例子,在一個非靜態方法中調用了靜態變數。唯一的不同是用了self。難道用了self就可以????不知道???需要一個實驗。

The static declaration must be after the visibility declaration. For compatibility with PHP4, if no visibility declaration is used, then the member or method will be treated as if it was declared as public.
靜態聲明必須必須是顯式的聲明。為了相容PHP4,如果沒有顯式聲明的對象或者方法,被當作聲明為public。

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.
因為靜態方法不需要執行個體化類對象來調用,所以偽變數$this在靜態方法中也是停用。

In fact static method calls are resolved at compile time. When using an explicit class name the method is already identified completely and no inheritance rules apply. If the call is done by self then self is translated to the current class, that is the class the code belongs to. Here also no inheritance rules apply.
實際上,靜態方法調用在編譯時間已經確定了。(這段我不會翻譯。???不明白???)
求了很久求來的翻譯如下:
------------------------------------------------
實際上,靜態方法的調用在編譯時間解決。當使用一個明確的類名時,方法已經被完全識別而不需要應用繼承規則。如果由自身調用,那麼自身被解析成當前的類,也就是代碼所屬的類。這裡也沒有應用繼承規則。
但是一個新的問題:
這裡不一定有繼承產生,為什麼會提到繼承規則?(???不明白????)

Static properties cannot be accessed through the object using the arrow operator ->. Calling non-static methods statically generates an E_STRICT level warning.
靜態成員不能被類的對象通過箭頭符號->來調用。靜態調用一個非靜態方法會導致一個E_STRICT層級的警告。

靜態成員例:

複製代碼 代碼如下:class Foo
{
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static;//注意這裡!!!!
//return $my_static;//這樣寫會不會出錯。需要實驗
}
}

class Bar extends Foo
{
public function fooStatic() {
return parent::$my_static;//注意這裡!!!!
}
}
print Foo::$my_static . " n";
$foo = new Foo();
print $foo->staticValue() . " n";
print $foo->my_static . " n"; // 未定義的"Property" my_static
// $foo::my_static is not possible
print Bar::$my_static . " n";
$bar = new Bar();
print $bar->fooStatic() . " n";

靜態方法例:
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.