Several notes on using static methods in PHP

怪我咯
Release: 2023-03-12 17:48:02
Original
1134 people have browsed it

This article mainly introduces several precautions for using static methods in PHP. It describes the skills and error-prone points of calling PHP static methods in the form of examples. It needs Friends can refer to

This articleInstance introduction several common precautions when using static methods in PHP. Share it with everyone for your reference. The specific method is as follows:

1. Even if the method in the class is not declared with static, but it does not use changeable class member variables, it is still available externallyOperator :: to call ;

2. The value of $this in a method called statically (using the :: operator) is determined by the context of the call Determined! Instead of defining his class !!

For example, the following code:

<?php 
class TestClass1 
{ 
  public $normal_v = &#39;normal_v from TestClass1&#39;; 
  public static $STATIC_V = &#39;STATIC_V from TestClass1&#39;; 
  public function test_func1() 
  { 
    echo $this->normal_v.&#39;<br />&#39;.self::$STATIC_V; 
  } 
} 
class TestClass2 
{ 
  public $normal_v = &#39;normal_v from TestClass2&#39;; 
  public static $STATIC_V = &#39;STATIC_V from TestClass2&#39;; 
  public function test_func2() 
  { 
    TestClass1::test_func1(); 
  } 
} 
$t2 = new TestClass2(); 
$t2->test_func2();
Copy after login

What will the output of this code be? I thought it would be normal_v from TestClass1
STATIC_V from TestClass1, the test found that I was actually wrong, the correct output is:

normal_v from TestClass2
STATIC_V from TestClass1

Explanation: Although test_func1() is It is defined in TestClass1, but it is called in TestClass2. Its internal $this variable is determined by TestClass2!

In fact, the relationship between these two classes should be a "bidirectional association".

Interested friends can test and run the example of this article, I believe there will be new gains!

The above is the detailed content of Several notes on using static methods in PHP. For more information, please follow other related articles on the PHP Chinese website!

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