標籤:ack general ict fine blog res another rom long
- $this偽變數
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
As of PHP 7.0.0 calling a non-static method statically from an incompatible context results in $this being undefined inside the method. Calling a non-static method statically from an incompatible context has been deprecated as of PHP 5.6.0.
As of PHP 7.0.0 calling a non-static method statically has been generally deprecated (even if called from a compatible context). Before PHP 5.6.0 such calls already triggered a strict notice.
即
1. 偽變數$this在object上下文中方法被調用時有效,它是"the calling object"的引用,(通常,the calling object 是方法所屬的對象。但是,也可能是其他對象,如果方法是從次級對象(我的理解是子類對象)的上下文中靜態調用)。
2. 如果靜態地調用一個非靜態方法,
例子:
1 <?php 2 class A 3 { 4 function foo() 5 { 6 if (isset($this)) { 7 echo ‘$this is defined (‘; 8 echo get_class($this); 9 echo ")\n";10 } else {11 echo "\$this is not defined.\n";12 }13 }14 }15 16 class B17 {18 function bar()19 {20 A::foo();21 }22 }23 24 error_reporting(E_ALL);25 26 $a = new A();27 $a->foo();28 29 A::foo(); //靜態調用非靜態方法30 $b = new B();31 $b->bar(); //從一個incompatibale context靜態調用非靜態方法32 33 B::bar(); //靜態調用非靜態方法bar(),然後在bar()中再次靜態調用非靜態方法34 ?>php 5.5.38執行效果
php 7.1.2執行效果
PHP 物件導向文法細節