PHP OOP更新了Extended类__ Construct上的受保护字符串



我正在尝试创建我的第一个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();

我要获得的结果是:

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

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

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

您可以使用: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();

将为您提供以下输出:

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)

对象在程序继续运行时不会影响类状态,这意味着这两个实例是彼此分开的。但是,您可以使用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();

输出:

The Test class has loaded (test)Updated to (changed)
The Test2 class has loaded (changed)The string has been updated to (updated)

最新更新