首頁  >  文章  >  後端開發  >  對PHPstatic的理解

對PHPstatic的理解

WBOY
WBOY原創
2016-08-08 09:26:30940瀏覽

最近看了下Yii2.0的源碼,發現裡面有很多new static() 和static::的語句,順便做下記錄
- 首先看下面程式碼

<code><span><span>class</span><span>A</span> {</span><span>public</span><span>static</span><span><span>function</span><span>get_self</span><span>()</span> {</span><span>return</span><span>new</span><span>self</span>();
    }

    <span>public</span><span>static</span><span><span>function</span><span>get_static</span><span>()</span> {</span><span>return</span><span>new</span><span>static</span>();
    }
}
<span><span>class</span><span>B</span><span>extends</span><span>A</span> {</span>}
<span>echo</span> get_class(B::get_self()); <span>// A</span><span>echo</span> get_class(B::get_static()); <span>// B</span><span>echo</span> get_class(A::get_static()); <span>// A</span></code>

透過上面可以看出new static() 表示的調用的類,而new self() 表示的是聲明的類

<code><span><span>class</span><span>A</span> {</span><span>const</span> TEST = <span>'testa'</span>;

    <span>public</span><span>static</span><span><span>function</span><span>test_static</span><span>()</span>{</span><span>echo</span><span>static</span>::TEST;
    }

    <span>public</span><span>static</span><span><span>function</span><span>test_self</span><span>()</span>
    {</span><span>echo</span><span>self</span>::TEST;
    }
}
<span><span>class</span><span>B</span><span>extends</span><span>A</span> {</span><span>const</span> TEST = <span>'testb'</span>;
}
<span>echo</span> B::test_static(); <span>//testb</span><span>echo</span> B::test_self(); <span>//testa</span></code>

透過上面的觀察可以得出一個結論,static和被呼叫的類別相關,而self則和聲明的類別(self程式碼所在的類別)相關。

以上就介紹了對PHPstatic的理解,包括了方面的內容,希望對PHP教程有興趣的朋友有幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn