我正在尝试创建我的第一个 PHP 类,但一直被困在如何更新 protected 字符串上。
我想做的是创建一个扩展类,该扩展类可以处理来自主类的 protected 字符串。
我能够在第一个类加载时更新字符串,但是当我加载我的扩展类时它不显示更新的文本。
我做错了什么?
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 类已加载(已更改) 字符串已更新为(updated)
最佳答案
您需要构建父级。仅仅因为子类扩展了父类,并不意味着父类在子类创建/构造时自动创建/构造。它只是继承了功能(属性/方法)。
您可以使用: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)
关于扩展类 __construct 上的 PHP OOP 更新 protected 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55071667/