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');
}
}
?>
That’s not how classes and inheritance work.
If you were to inspect
$B, itsmyvarvalue would be “hello”. Nothing in your code will modify the value of$a->myvar.If you want the declaration of
$Bto modify anAobject’s member variables, you need to pass that object to the constructor: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.