题目描述
<?php
declare(strict_types=1);
class staticparent {
static $parent_only;
static $both_distinct;
function __construct() {
static::$parent_only = 'fromparent';
static::$both_distinct = 'fromparent';
//self::$parent_only = 'fromparent';
// self::$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';
// self::$parent_only = 'fromchild';
// self::$both_distinct = 'fromchild';
// self::$child_only = 'fromchild';
}
}
$a = new staticparent;
$a = new staticchild;
echo 'Parent: parent_only=', staticparent::$parent_only, ', both_distinct=', staticparent::$both_distinct, "<br/>\r\n";
echo 'Child: parent_only=', staticchild::$parent_only, ', both_distinct=', staticchild::$both_distinct, ', child_only=', staticchild::$child_only, "<br/>\r\n";
?>
题目来源及自己的思路
输出
Parent: parent_only=fromchild, both_distinct=fromparent
Child: parent_only=fromchild, both_distinct=fromchild, child_only=fromchild
https://www.php.net/manual/zh...
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
$a = new staticparent;
var_dump(get_class_vars("staticparent"));
$a = new staticchild;
echo "<hr>";
var_dump(get_class_vars("staticparent"));
出现以下结果
array(2) { ["parent_only"]=> string(10) "fromparent" ["both_distinct"]=> string(10) "fromparent" }
array(2) { ["parent_only"]=> string(9) "fromchild" ["both_distinct"]=> string(10) "fromparent" }
我想咨询下,为什么new staticchild
后父类的parent_only会被修改,而both_distinct却不会.
另外输出的原因是什么,而且把注释里面self::打开,替换static,结果为何是一致
Parent: parent_only=fromchild, both_distinct=fromparent
Child: parent_only=fromchild, both_distinct=fromchild, child_only=fromchild
因为被覆盖了啊
staticchild
没有$parent_only
,所以
staticchild::$parent_only
调用的是staticparent
的$parent_only
而
staticparent
的$parent_only
被设置了fromchild
所以打印出了
fromchild
另外静态绑定不是这么用的。
子类继承父类覆盖了a属性。
当子类的一个实例对象调用父类一个获取或使用a属性方法时,一般情况下,使用的是父类的a属性。
而静态绑定,则使用的是子类自身的a属性。
概况起来就是谁的对象用谁的