[英]Why does PHP assume this variable is a string when it hasn't been used anywhere yet?
I have two classes: 我有两节课:
class BaseResource {
public $url;
protected $relativeUrl;
protected $parentUrl;
public function BaseResource($relUrl, $parentUrl) {
$this->relativeUrl = $relUrl;
$this->parentUrl = $parentUrl;
$this->url = url_to_absolute($parentUrl, $relUrl);
}
}
class XMLResource extends BaseResource {
private $xml;
public function XMLResource($relUrl, $parentUrl, $xml) {
parent::BaseResource($relUrl, $parentUrl);
$this->$xml = $xml;
}
}
It's all very simple stuff, but when I execute the following code I get an error. 这些都是非常简单的东西,但是当我执行以下代码时,我得到一个错误。
$relUrl = "../something.html";
$parentUrl = "http://example.com/test/index.php";
$xml = new DOMDocument();
$xmlRes = new XMLResource($relUrl, $parentUrl, $xml);
Catchable fatal error: Object of class DOMDocument could not be converted to string
可捕获的致命错误:DOMDocument类的对象无法转换为字符串
Why is it being assumed that XMLResource::xml
is a string? 为什么假定
XMLResource::xml
是字符串? I haven't used it yet so I would assume it is undefined until it is set and then it takes on the type of whatever it is set to? 我还没有使用过它,所以我假设它在设置之前是不确定的,然后采用它设置为什么类型?
It's not that easy to spot, you're in the right line: 发现并不是那么容易,您处于正确的位置:
$this->$xml = $xml;
But you must look only at this part: 但是您必须只看这一部分:
$this->$xml
Do this instead: 改为这样做:
$this->xml = $xml;
Background: PHP tries to use the content of $xml
as the literal variable name, which does not work in your case because it needs a string and you're providing an object (which has no __toString()
method). 背景:PHP尝试将
$xml
的内容用作文字变量名称,这种情况在您的情况下不起作用,因为它需要一个字符串并且您要提供一个对象(没有__toString()
方法)。
The feature is called Variable variables Docs . 该功能称为“ 变量变量文档” 。
I'm not sure why PHP is assuming $xmlRes->xml
is a string but you have an error in your XMLResource
function: 我不确定为什么PHP假设
$xmlRes->xml
是一个字符串,但是XMLResource
函数中有一个错误:
$this->$xml = $xml;
should be: 应该:
$this->xml = $xml;
$this->$xml = $xml;
应该
$this->xml = $xml;
You made 1 tiny mistake, change $this->$xml = $xml;
您犯了一个小错误,更改
$this->$xml = $xml;
to $this->xml = $xml;
到
$this->xml = $xml;
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.