php在实例化类中设置变量值

时间:2018-06-20 11:56:17

标签: php oop

如何在实例化我的类中设置值或调用方法?参见下面的代码

class Father {
    public $foo = '';
}
class Son {
    function setFoo($value){
        //this is the part that I need
    }
}

$father = new Father();
$father->son = new Son();
$father->son->setFoo('bar');
echo $father->foo; //I want it to now be 'bar'

2 个答案:

答案 0 :(得分:1)

一个答案建议继承,这在父子方式中很有意义。但是,如果您不希望这样做,也许您正在寻找依赖项注入(构造函数注入)方法。

<?php

class Father 
{
    private $son;

    private $foo = '';

    function getFoo()
    {
        return $this->foo;
    }

    function setFoo($value)
    {
        $this->foo = $value;
    }
}

class Son 
{
    private $father;

    public function __construct(Father $dad)
    {
        $this->father = $dad;
    }

    function setFoo($value)
    {
        $this->father->setFoo($value);
    }
}

$father = new Father();
$son = new Son($father);

$son->setFoo('bar');

echo $father->getFoo(); // 'bar'

在这里https://3v4l.org/hUQve

查看

答案 1 :(得分:-2)

您的子类需要从父类继承。

class Father {
    public $foo = '';
}

class Son extends Father {
    function setFoo($value){
        //this is the part that I need
        $this->foo = $value ;
    }
}