Home > Backend Development > PHP Tutorial > PHP使用静态方法的几个注意事项_php技巧

PHP使用静态方法的几个注意事项_php技巧

WBOY
Release: 2016-05-16 20:36:09
Original
952 people have browsed it

本文实例介绍了PHP使用静态方法的几个常见注意事项。分享给大家供大家参考。具体方法如下:

1. 即使类中的方法并未用static声明,但其未使用到可改变的类成员变量,在外部仍可用操作符::来调用

2. 以静态方式(用::操作符)调用的方法中$this的取值是由调用时的上下文决定的!而不是定义他的类!!

例如以下的代码:

<&#63;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.'<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(); 
  } 
} 
$t2 = new TestClass2(); 
$t2->test_func2(); 

Copy after login

这段代码是输出会是什么呢,我原以为会是normal_v from TestClass1
STATIC_V from TestClass1,测试发现其实我错了,正确的输出是:

normal_v from TestClass2
STATIC_V from TestClass1

说明:test_func1()虽然是在TestClass1中定义的,但却是在TestClass2中调用的,其内部的$this变量则是由TestClass2决定的!

其实这两个类的关系应该属于"双向关联".

感兴趣的朋友可以测试运行本文实例,相信会有新的收获!

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