Rumah  >  Artikel  >  pembangunan bahagian belakang  >  对PHPstatic的理解

对PHPstatic的理解

WBOY
WBOYasal
2016-08-08 09:26:30942semak imbas

最近看了下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教程有兴趣的朋友有所帮助。

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn