【问题标题】:Calling static functions with $this [duplicate]使用 $this 调用静态函数 [重复]
【发布时间】:2020-01-13 12:11:28
【问题描述】:

我在胡闹,发现您实际上可以使用$this->method() 调用静态方法

这让我对调用静态方法的 3 种方式(据我所知)之间的区别感到有些困惑和好奇

$this->method();
static::method();
self::method();

现在,我想我明白后两者的区别了,但是第一个呢?

【问题讨论】:

    标签: php static


    【解决方案1】:

    了解类继承上下文中静态属性的行为很重要:

    在父类和子类中定义的静态属性将保存每个类的 DISTINCT 值。正确使用 self::static:: 在子方法内部引用预期的静态属性至关重要。

    仅在父类中定义的静态属性将共享一个 COMMON 值。

    declare(strict_types=1);
    
    class staticparent {
        static    $parent_only;
        static    $both_distinct;
    
        function __construct() {
            static::$parent_only = 'fromparent';
            static::$both_distinct = 'fromparent';
        }
    }
    
    class staticchild extends staticparent {
        static    $child_only;
        static    $both_distinct;
    
        function __construct() {
            static::$parent_only = 'fromchild';
            static::$both_distinct = 'fromchild';
            static::$child_only = 'fromchild';
        }
    }
    
    $a = new staticparent;
    $a = new staticchild;
    

    更多关于https://www.php.net/manual/en/language.oop5.static.php

    【讨论】:

      【解决方案2】:

      self 用于类中的静态方法和变量

      $this 用于非静态方法和变量

      static一般使用调用子类的静态方法或变量 比如后期静态

      例如late static binding

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-04
        • 2011-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-25
        相关资源
        最近更新 更多