Search code examples
phpoopvariable-types

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

Why is it being assumed that XMLResource::xml is a string? 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?


Solution

  •     $this->$xml = $xml;
    

    should be

    $this->xml = $xml;