dongwu9063 2014-04-24 14:37
浏览 55
已采纳

哪些PHP函数使用__toString

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
  • 写回答

1条回答 默认 最新

  • duanbo1659 2014-04-24 14:46
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题