Heim  >  Artikel  >  php教程  >  PHP使用静态方法的几个注意事项

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

WBOY
WBOYOriginal
2016-06-13 09:25:201145Durchsuche

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

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

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

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

例如以下的代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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();

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

normal_v from TestClass2
STATIC_V from TestClass1

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

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

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn