本文介绍了在扩展类中修改父类的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在类B中调用函数replace来替换类A中的变量。在下面的代码中,我想将 hi替换为 hello,但输出为 hi

PS:类B是某些控制器,必须在类A中获得实例。

我正在使用php 5.2.9 +

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.

<?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 的值。

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

如果要声明 $ B 修改 A 对象的成员变量,您需要将该对象传递给构造函数:

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.

这篇关于在扩展类中修改父类的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 13:36