首页 > 代码库 > PHP 面向对象语法细节

PHP 面向对象语法细节

  1. $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 面向对象语法细节