我想要具有最终构造函数的扩展类(在我的情况下它是 SimpleXMLElement),但是我遇到了问题,因为当我使用时:
class myclass extends SimpleXMLElement {
function __construct($xmlVersion='1.0', $xmlEncoding='ISO-8859-1', $rootName='root'){
parent::__construct("<?xml version='$xmlVersion' encoding='$xmlEncoding'?><$rootName />");
}
Run Code Online (Sandbox Code Playgroud)
我得到错误:
致命错误:无法覆盖最终方法 SimpleXMLElement::__construct()
当我删除构造函数时,出现此错误:
致命错误:未捕获的异常“异常”,消息为“SimpleXMLElement::__construct() 需要至少 1 个参数,给定 0”
我错过了一些东西或不明白如何正确调用最终的父构造函数。我不想覆盖方法只是扩展类,但我无法扩展,因为它需要 __construct()。所以我错过了一些东西,然后又回到了开始的地方。
有人可以解释我错在哪里吗?
我刚刚经历了这件事。你不需要扩展它。创建一个包含 SimpleXMLElement 对象的类。我相信这就是尼古拉的意思。
class XmlResultSet
{
public $xmlObjs = array();
public function __construct(array $xmlFiles)
{
foreach ($xmlFiles as $file) {
$this->xmlObjs[] = new XmlResult($file);
}
}
}
class XmlResult
{
private $xmlObj;
public function __construct($file)
{
try {
$this->xmlObj = new SimpleXMLElement($file, 0, true);
}
catch (Exception $e) {
throw new MyException("Invalid argument ($this)($file)(" . $e .
")", PHP_ERRORS);
}
}
public function otherFunctions()
{
return $this->xmlObj->movie['name']; // whatever
}
}
Run Code Online (Sandbox Code Playgroud)