在扩展类中使用变量的新值

时间:2019-05-18 17:47:12

标签: php class

这是我的示例代码:

class Dad {
    protected $name = 'Alex';

    public function setName($string)
    {
        $this->name = $string;
    }
}


class Son extends Dad{

    public function showName()
    {
        return $this->name;
    }
}

我使用这样的类:

            $dad = new Dad();
            $dad->setName('John');


            $son = new Son();
            echo $son->showName();//it echo Alex but i need to echo John

我在父类和子类中使用了许多受保护的变量,这仅是示例。 我如何使用子类中受保护变量的新值?

1 个答案:

答案 0 :(得分:0)

您有2个对象。对象中的默认名称为“ Alex”。因此,当您创建一个新对象而没有明确为其命名时,它将使用'Alex',因为这是默认设置。

$p = new Dad;
// name is Alex.

$q = new Son;
// name is Alex

$p->setName('John'); // Now the name of $p is John
$q->setName('Beto'); // Now the name of $q is Beto. $p remains unchanged.

这是对象的要点,它们是分开的。

如果您想要更改默认名称的方法,则可以执行此操作。

class Dad
{
    protected $name;
    static protected $defaultName = 'Alex';
    public function __construct()
    {
        $this->name = self::$defaultName;
    }
    public function showName()
    {
        return $this->name;
    }
    public static function setDefault($name)
    {
        self::$defaultName = $name;
    }
}

现在:

$p = new Dad; // $p->name is 'Alex'
Dad::setDefault('Bernie');
$q = new Dad; // $q->name is 'Bernie', $p is not changed
$r = new Dad; // $r->name is 'Bernie'
Dad::setDefault('Walt');
$t = new Dad; // $t->name is Walt

希望这会有所帮助。

相关问题