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 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?