Understanding PHPstatic

WBOY
Release: 2016-08-08 09:26:30
Original
889 people have browsed it

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>
Copy after login

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>
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!