modify parent class's variable in extended cla

2019-09-07 08:17发布

问题:

I wanna replace a variable in class A by calling function replace in class B. e.g. in code below I want replace 'hi' for 'hello' but output is 'hi'
P.S : class B is some controller and must get instance in class A.
i'm using php 5.2.9+

<?php
$a = new A();
class A {
    protected $myvar;

    function __construct() {
        $this->myvar = "hi";
        $B = new B();
        echo $this->myvar; // expected value = 'hello', output = 'hi'
    }

    function replace($search, $replace) {
        $this->myvar = str_replace($search, $replace, $this->myvar);
    }
}

class B extends A {
    function __construct() {
        parent::replace('hi', 'hello');
    }
}
?>

回答1:

That's not how classes and inheritance work.

<?php
$a = new A();
class A {
    protected $myvar;

    function __construct() {
        $this->myvar = "hi";

        /**
         * This line declares a NEW "B" object with its scope within the __construct() function
         **/
        $B = new B();

        // $this->myvar still refers to the myvar value of class A ($this)
        // if you want "hello" output, you should call echo $B->myvar;
        echo $this->myvar; // expected value = 'hello', output = 'hi'
    }

    function replace($search, $replace) {
        $this->myvar = str_replace($search, $replace, $this->myvar);
    }
}

class B extends A {
    function __construct() {
        parent::replace('hi', 'hello');
    }
}
?>

If you were to inspect $B, its myvar value would be "hello". Nothing in your code will modify the value of $a->myvar.

If you want the declaration of $B to modify an A object's member variables, you need to pass that object to the constructor:

class A {
    .
    .
    .

    function __construct() {
         .
         .
         .
         $B = new B($this);
         .
         .
         .
    }
}
class B extends A {
    function __construct($parent) {
        $parent->replace('hi', 'hello');
    }
}

Note: This is a very poor implementation of inheritance; though it does what you "want" it to do, this is not how objects should interact with each other.



回答2:

Little Modification on your script would do the trick> Its messy but i get you want call the parent first

$a = new A();
class A {
    protected $myvar;

    function __construct() {
        $this->myvar = "hi";
        $B = new B($this);
        echo $this->myvar; // expected value = 'hello', output = 'hi'
    }

    function replace($search, $replace) {
        $this->myvar = str_replace($search, $replace, $this->myvar);
    }
}

class B extends A {
    function __construct($a) {
        $a->replace('hi', 'hello');
    }
}


回答3:

Currently, you're creating an instance of A class, then you'll never call the B::replace() function.

Change this line :

$a = new A();

into

$b = new B();


标签: php class