扩展类__construct上的PHP OOP更新受保护的字符串

Ste*_*yne 5 php oop

我正在尝试创建我的第一个PHP类,并一直停留在如何更新受保护的字符串上。

我想做的是创建一个扩展类,该扩展类与主类中的受保护字符串一起使用。

加载第一个类时,我可以更新字符串,但是加载扩展类时,它不显示更新后的文本。

我究竟做错了什么?

class test {
    protected $testing = 'test';

    function __construct(){
        echo "The Test class has loaded (".$this->testing.")";
        $this->testing='changed';
        echo "Updated to (".$this->testing.")";
    }
}

class test2 EXTENDS test {

    function __construct(){
        echo "The Test2 class has loaded (".$this->testing.")";
        $this->testing='updated';
        echo 'The string has been updated to ('.$this->testing.')';
    }
}

$blah = new test();
$blah2 = new test2();
Run Code Online (Sandbox Code Playgroud)

我想要得到的结果是:

Test类已经加载(测试),更新为(更改)

Test2类已加载(已更改)字符串已更新为(已更新)

dom*_*gia 5

您需要构造父代。仅仅因为子类扩展了父类,并不意味着在子类存在时会自动创建/构造父类。它只是继承功能(属性/方法)。

您可以执行以下操作: parent::__construct();

我对您的源代码做了一些小修改,尤其是PSR-2样式的类名和换行符。但是其他一切都一样。

<?php

class Test {
    protected $testing = 'original';

    function __construct(){
        echo "The Test class has loaded (".$this->testing.")\n";
        $this->testing = 'Test';
        echo "Updated to (".$this->testing.")\n";
    }
}

class TestTwo extends test {

    function __construct(){
        echo "Child class TestTwo class has loaded (".$this->testing.")\n";
        parent::__construct();
        echo "Parent class Test class has loaded (".$this->testing.")\n";
        $this->testing = 'TestTwo';
        echo "The string has been updated to (".$this->testing.")\n";
    }
}

$test = new Test();
$testTwo = new TestTwo();
Run Code Online (Sandbox Code Playgroud)

这将为您提供以下输出:

The Test class has loaded (original)
Updated to (Test)
Child class TestTwo class has loaded (original)
The Test class has loaded (original)
Updated to (Test)
Parent class Test class has loaded (Test)
The string has been updated to (TestTwo)
Run Code Online (Sandbox Code Playgroud)


rev*_*evo 4

当程序继续运行时,对象不会影响类状态,这意味着这两个实例化彼此分开。但是,您可以保留对类的更改,而不是使用static属性:

class test
{
    protected static $testing = 'test';

    function __construct()
    {
        echo "The Test class has loaded (" . self::$testing . ")";
        self::$testing = 'changed';
        echo "Updated to (" . self::$testing . ")";
    }
}

class test2 extends test
{
    function __construct()
    {
        echo "The Test2 class has loaded (" . self::$testing . ")";
        self::$testing = 'updated';
        echo 'The string has been updated to (' . self::$testing . ')';
    }
}

$blah = new test();
echo PHP_EOL;
$blah2 = new test2();
Run Code Online (Sandbox Code Playgroud)

输出:

The Test class has loaded (test)Updated to (changed)
The Test2 class has loaded (changed)The string has been updated to (updated)
Run Code Online (Sandbox Code Playgroud)