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.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化