我正在尝试创建我的第一个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();
我想要得到的结果是:
Test类已加载(测试) 更新为(已更改)
Test2类已加载(已更改) 字符串已更新为(更新)
答案 0 :(得分: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();
将为您提供以下输出:
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)
答案 1 :(得分: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();
输出:
The Test class has loaded (test)Updated to (changed)
The Test2 class has loaded (changed)The string has been updated to (updated)