Several considerations for using static methods in PHP

Source: Internet
Author: User

This article illustrates several common considerations for using static methods in PHP. Share to everyone for your reference. The specific methods are as follows:

1. Even if the method in the class is not declared with static, but it is not used to the variable class member variables, the operator can still be used externally:: to invoke;

2. The value of the $this in a method invoked in a static manner (by:: operator) is determined by the context in which it is invoked! Not the class that defines him!!

For example, the following code:

1 2 3 4 5 6 7 8 9, <?php  class testclass1  {    public $normal _v = ' No Rmal_v from TestClass1 ';    public static $STATIC _v = ' static_v from TestClass1 ';     Public Function test_func1 ()     {      echo $this->normal_v. ' <br/> '. Self:: $STATIC _v;    } }  class testclass2  {    public $normal _v = ' Normal_v from TestClass2 ';    public static $STATIC _v = ' static_v from TestClass2 ';     Public Function Test_func2 ()     {      testclass1::test_func1 ();    } }  $t 2 = new TestClass2 ();  $t 2->test_func2 ();

This code is what the output will be, I thought it would be normal_v from TestClass1 <br/> Static_v from TestClass1, the test found that I was wrong, the correct output is:

Normal_v from TestClass2
Static_v from TestClass1

Description: Test_func1 () Although it is defined in the TestClass1, but is called in the TestClass2, its internal $this variable is determined by the TESTCLASS2!

In fact, the relationship between these two classes should belong to "bidirectional association".

Interested friends can test run this example, I believe there will be a new harvest!

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.