开发者

In what scenario would one need to use PHPs magic function toString()

Why would a programmer need to use the function? How would the same results have been achieved in php 4开发者_开发问答?


In any scenario where you want to control how an object behaves when used in a string context (used as a string), e.g.

class FullName
{
    protected $firstName;
    protected $middleNames = array();
    protected $lastName;

    // ... methods ...

    public function __toString()
    {
        return sprintf('%s %s %s', $this->firstName,
                                   implode(' ', $this->middleNames),
                                   $this->lastName);
    }
}

$fullname = new FullName('John', array('Jim', 'Jamie'), 'Jackson');
echo "Hello, my name is $fullname";

You cannot simulate this method in PHP4. In fact, you shouldn't even be using PHP4 anymore at all.


Please see this question. If its available, its preferable to casting to achieve the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜