Question

Which PHP functions call an objects __toString method when passed an object?

Take the following example:

class url {

    protected $url;

    function __construct($url) {
        $this->setUrl($url);
    }

    public function setUrl($url) {
        $this->url = $url;
    }

    public function getUrl() {
        return $this->url;
    }

    public function __toString() {
        return $this->getUrl();
    }

}

$url = new url('http://example.com');
var_dump(in_array($url,array('http://example.com')));

The call to in_array evaluates to true when passed the url object.

The following also evaluates to true, but what is it doing internally, is it comparing two objects or two strings?

var_dump(in_array($url,array($url)));

Would it be better to explicitly say strings should be compared?

var_dump(in_array((string)$url,array('http://example.com')));

Do all PHP functions similar to in_array see an object as a string if it has a __toString method or is it just some of them? Therefore would it be better to explicitly say (string) before passing an object?

Examples for testing == comparison.

$url = new url('http://example.com');
$url2 = new url('http://example.com');
var_dump(in_array($url,array('http://example.com'))); #1
var_dump(in_array($url,array($url))); #2
var_dump(in_array($url,array($url2))); #3
Was it helpful?

Solution

From the documentation:

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

So, in answer to your question about in_array, it appears that the two objects are compared using the comparison operator (==). There is no conversion to string (via __toString() or any other way) before comparison.

More generally, I have found this to be the case for almost all objects in PHP - the only exceptions are classes that encapsulate system resources, like PDO or objects like closures (for reasons that I don't fully understand).

It is not necessary to cast the object(s) to strings before doing the comparison.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top