Considerations for using static methods in PHP

Source: Internet
Author: User
This article mainly introduces several considerations for using static methods in PHP, and describes the PHP static method calling techniques and error points in the form of examples, for more information about PHP static methods, see the following examples. Share it with you for your reference. The specific method is as follows:

1. even if the methods in the class are not declared as static, but they do not use variable members of the changeable class, they can still be called using the external operator;

2. the value of $ this in the method called in static mode (with: operator) is determined by the context during the call! Instead of defining its class !!

For example, the following code:

<?php class TestClass1 {   public $normal_v = 'normal_v from TestClass1';   public static $STATIC_V = 'STATIC_V from TestClass1';   public function test_func1()   {     echo $this->normal_v.'
'.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(); } } $t2 = new TestClass2(); $t2->test_func2();

What is the output of this code? I thought it would be normal_v from TestClass1.
STATIC_V from TestClass1. the test shows that I am wrong. the correct output is:

Normal_v from TestClass2
STATIC_V from TestClass1

Note: Although test_func1 () is defined in TestClass1, it is called in TestClass2. the internal $ this variable is determined by TestClass2!

In fact, the relationship between these two classes should belong to "two-way Association ".

If you are interested, you can test and run this article. I believe there will be new gains!

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.