首页  >  文章  >  后端开发  >  对PHPstatic的理解

对PHPstatic的理解

WBOY
WBOY原创
2016-08-08 09:26:30939浏览

最近看了下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