PHP使用静态方法最好不要和对象混合使用,如果你没搞清楚的话,就不要用了
PHP使用静态方法最好不要和对象混合使用,如果你没搞清楚的话,就不要用了
1. 即使类中的方法并未用static声明,但其未使用到可改变的类成员变量,在外部仍可用操作符::来调用;
2. 以静态方式(用::操作符)调用的方法中$this的取值是由调用时的上下文决定的! 而不是定义他的类!!
例如以下的代码:
<?php class TestClass1 { public $normal_v = 'normal_v from TestClass1'; public static $STATIC_V = 'STATIC_V from TestClass1'; public function test_func1() { print_r($this); echo $this->normal_v."\n".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 <br /> STATIC_V from TestClass1,测试发现其实我错了,正确的输出是:
object(TestClass2)#1 (1) { ["normal_v"]=> string(24) "normal_v from TestClass2" } normal_v from TestClass2 STATIC_V from TestClass1
你会发现静态方法里的$this 其实是根据上下文context 来定义的!
说明:test_func1()虽然是在TestClass1中定义的,但却是在TestClass2中调用的,其内部的$this变量则是由TestClass2决定的!
其实这两个类的关系应该属于"双向关联".