Home  >  Article  >  Backend Development  >  Understanding PHPstatic

Understanding PHPstatic

WBOY
WBOYOriginal
2016-08-08 09:26:30940browse

I recently looked at the source code of Yii2.0 and found that there are a lot of new static() and static:: statements in it, so I took a note of it
- First look at the code below

<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>

You can see from the above that new static() represents the calling class, and new self() represents the declared class

<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>

From the above observations, we can draw a conclusion , static is related to the called class, and self is related to the declared class (the class where the self code is located).

The above has introduced the understanding of PHPstatic, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn