【发布时间】:2020-01-13 12:11:28
【问题描述】:
我在胡闹,发现您实际上可以使用$this->method() 调用静态方法
这让我对调用静态方法的 3 种方式(据我所知)之间的区别感到有些困惑和好奇
$this->method();
static::method();
self::method();
现在,我想我明白后两者的区别了,但是第一个呢?
【问题讨论】:
我在胡闹,发现您实际上可以使用$this->method() 调用静态方法
这让我对调用静态方法的 3 种方式(据我所知)之间的区别感到有些困惑和好奇
$this->method();
static::method();
self::method();
现在,我想我明白后两者的区别了,但是第一个呢?
【问题讨论】:
了解类继承上下文中静态属性的行为很重要:
在父类和子类中定义的静态属性将保存每个类的 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;
【讨论】:
self用于类中的静态方法和变量
$this用于非静态方法和变量
static一般使用调用子类的静态方法或变量 比如后期静态
【讨论】: