我想通过在B类中调用函数replace来替换A类中的变量。在下面的代码中,我想将'hi'替换为'hello',但输出为'hi'
P.S:B类是一些控制器,必须在A类中得到实例。
我正在使用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');
}
}
?>
答案 0 :(得分:3)
这不是类和继承的工作方式。
<?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');
}
}
?>
如果您要检查$B
,其myvar
值将为“hello”。代码中的任何内容都不会修改$a->myvar
的值。
如果您希望声明$B
来修改A
对象的成员变量,则需要将该对象传递给构造函数:
class A {
.
.
.
function __construct() {
.
.
.
$B = new B($this);
.
.
.
}
}
class B extends A {
function __construct($parent) {
$parent->replace('hi', 'hello');
}
}
注意:这是一种非常糟糕的继承实现;虽然它做了你“想要”它做的事情,但这不是应该彼此互动的方式。
答案 1 :(得分:2)
对您的脚本进行少量修改就可以了解&gt;它很乱,但我想让你先打电话给父母
$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');
}
}
答案 2 :(得分:1)
目前,您正在创建A
类的实例,然后您将永远不会调用B::replace()
函数。
更改此行:
$a = new A();
进入
$b = new B();