简体   繁体   English

子班影响父母班

[英]Child class affects parent class

Here is my code: 这是我的代码:

class Parent1
{
    static $db = null;

    public function __construct()
    {
        self::$db = 'a';
    }
}

class Child extends Parent1
{

    public function __construct()
    {
        parent::__construct();
        self::$db = 'b';
    }
}

$myParent = new Parent1();
echo $myParent::$db; //"a"

$myChild = new Child();
echo $myChild::$db; //"b"
echo $myParent::$db; //"b" it should be "a"

Why $myParent::$db is changing to b ? 为什么$myParent::$db更改为b How to prevent it?? 如何预防呢?

Why? 为什么?

static $db = null;

$db is static , it's not linked to the instance. $dbstatic ,它没有链接到实例。
self::$db = 'b'; will change the unique and shared instance of $db . 将更改$db的唯一共享实例。

How to prevent it? 怎么预防呢?

You can't. 你不能 It's how static fields work. 这就是static字段的工作方式。
By the way, calling static from an instance ( $aa::field ) is not a good think. 顺便说一句,从实例( $aa::field )调用static不是一个好主意。

Take a look at the documentation about static in PHP because you probably don't understand how it work. 查看有关PHP中静态文档,因为您可能不了解它的工作原理。

You are using static variables. 您正在使用静态变量。 These are class level and shared across all instances. 这些是类级别的,并且在所有实例之间共享。 You might want to change them to instance variables... see below. 您可能想将它们更改为实例变量...请参见下文。

<?php
class Parent1
{
    public $db = null;

    public function __construct()
    {
        $this->db = 'a';
    }
}

class Child extends Parent1
{

    public function __construct()
    {
        parent::__construct();
        $this->db = 'b';
    }
}

However, writing to $myChild->db WILL change the variable from the parent because it is an inherited variable but it won't affect the $db value from $myParent. 但是,写入$ myChild-> db会更改父项中的变量,因为它是继承的变量,但不会影响$ myParent中的$ db值。

I found solution. 我找到了解决方案。 I redeclare static in Child - now it works. 我在Child中重新声明了static-现在可以使用了。 Thanks for explaining static 感谢您解释静态

class Parent1
{
    static $db = null;

    public function __construct()
    {
        self::$db = 'a';
    }
}

class Child extends Parent1
{
    static $db = null;

    public function __construct()
    {
        parent::__construct();
        self:$db=parent::$db;
        self::$db = 'b';
    }
}

$myParent = new Parent1();
echo $myParent::$db; //"a"

$myChild = new Child();
echo $myChild::$db; //"b"
echo $myParent::$db; //"a" => as it should

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM