php - 从另一个 PHP 类设置 protected 变量的正确方法

标签 php class variables get set

我有这个问题要解决: 我创建了两个类,其中第二个是第一个的扩展,我想在那里 从头等舱设置并获取一个变量,但是......我找不到“正确”的方法 基本上是这样的:

class class_one {

    protected $value;
    private $obj_two;

    public function __construct() {
        $this->obj_two = new class_two;
    }

    public function firstFunction() {

        $this->obj_two->obj_two_function();

        echo $this->value; // returns 'New Value' like set in the class two

    }

}

class class_two extends one {   
    public function obj_two_function() {    
        "class_one"->value = 'New Value';   
    } 
}

我该怎么做?

最佳答案

第一个类不应该初始化第二个,除非你正在寻找 Uroboros! protected 变量可以在没有任何函数支持的情况下由扩展类设置。只是去 $this->protVariable = "stuff";

但是您将需要一个可能 protected 函数来设置来自第二个类的 ClassOne 的私有(private)变量。同样,必须在 ClassOne 中创建一个函数来实际检索它的值。

class ClassOne {
    private $privVariable;
    protected $protVariable;

    /**
     */
    function __construct () {

    }

    /**
     * This function is called so that we may set the variable from an extended
     * class
     */
    protected function setPrivVariable ($privVariable) {

        $this->privVariable = $privVariable;

    }

}

然后在第二个类中,您可以调用 parent::setPrivVariable() 以使用父函数设置值。

class ClassTwo extends \ClassOne {

    /**
     */
    public function __construct () {

        parent::__construct ();

    }

    /**
     * Set the protected variable
     */
    function setProtVariable () {

        $this->protVariable = "stuff";

    }

    /**
     * see ClassOne::setPrivVariable()
     */
    public function setPrivVariable ($privVariable) {

        parent::setPrivVariable ( $privVariable );

    }

}

关于php - 从另一个 PHP 类设置 protected 变量的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26535535/

相关文章:

c++ - 是什么让静态变量只初始化一次?

php - 优化 Trie 实现

php - 如何获取另一个表的外键引用的主键?

python - 如何在Python中创建多个类实例?

SQL Server 2005 SP 中有条件地分配变量

java - 添加项目 - 不同的变量名称

php - 使用 bootstrap 3 在自定义主题中注册和使用菜单

php - Wordpress $wpdb->在每个帖子的自定义表上插入两行

class - 一起使用表单和类的 VBA Excel 最佳实践?

class - 在 Dart 中,从变量调用静态方法时出现问题