PHP 面向对象语法细节

Posted jade640

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 5.6.0之前,不论from an incompatible context 或者 from compatible context 静态调用非静态方法都会触发a strict notice,从incompatible context静态调用非静态方法$this对象是secondary object的引用,如下面例子中的31行,最后输出指明$this指向B类的对象。
              2. 在PHP 5.6.0之后,from an incompatible context静态调用一个非静态方法会引发deprecated。其他情况静态调用非静态方法会触发a strict notice。并且from an incompatible context 静态调用一个非静态方法,非静态方法中的$this伪变量保存secondary object的引用
              3. 在PHP 7.0.0之后,不论是从an incompatible context 或者 from compatibel context 静态调用非静态方法,都会引发deprecated。在PHP7.0.0中,from an incompatible context 静态调用非静态方法会导致非静态方法内的$this伪对象是undefined,与PHP 7.0.0之前,$this伪对象是secondary object 的引用不同。
    例子:
     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 B
    17 {
    18     function bar()
    19     {
    20         A::foo();
    21     }
    22 }
    23 
    24 error_reporting(E_ALL);
    25 
    26 $a = new A();
    27 $a->foo();                 //从compatible context调用方法
    28 
    29 A::foo();                //从compatible context 静态调用非静态方法
    30 $b = new B();
    31 $b->bar();                //从一个incompatibale context静态调用非静态方法
    32 
    33 B::bar();                 //从compatible context 静态调用非静态方法bar(),然后在bar() 从compatible context中再次静态调用非静态方法
    34 ?>
    php 5.5.38执行效果


    php 5.6.30执行效果


    php 7.1.2执行效果
     

以上是关于PHP 面向对象语法细节的主要内容,如果未能解决你的问题,请参考以下文章

2017 5 31 php面向过程 面向对象1

PHP面向对象之选择工厂和更新工厂

VSCode自定义代码片段——JS中的面向对象编程

VSCode自定义代码片段9——JS中的面向对象编程

php面向对象基础

php面向对象