简体   繁体   中英

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 ? How to prevent it??

Why?

static $db = null;

$db is static , it's not linked to the instance.
self::$db = 'b'; will change the unique and shared instance of $db .

How to prevent it?

You can't. It's how static fields work.
By the way, calling static from an instance ( $aa::field ) is not a good think.

Take a look at the documentation about static in PHP because you probably don't understand how it work.

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.

I found solution. I redeclare static in Child - now it works. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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