为什么在PHP的何处以及为什么使用__toString()? [英] Where and why do we use __toString() in PHP?

查看:85
本文介绍了为什么在PHP的何处以及为什么使用__toString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解它是如何工作的,但是为什么我们实际上会使用它呢?

I understand how it works but why would we practically use this?

<?php
    class cat {
        public function __toString() {
            return "This is a cat\n";
        }
    }

    $toby = new cat;
    print $toby;
?>

与以下不同吗?

<?php
    class cat {
        public function random_method() {
            echo "This is a cat\n";
        }
    }

    $toby = new cat;
    $toby->random_method();
?>

我们不能只使用任何其他公共方法来输出任何文本吗? 为什么我们需要像这样的魔术方法?

can't we just use any other public method to output any text? Why do we need magic method like this one?

推荐答案

您不需要它".但是定义它可以使您的对象隐式转换为字符串,这很方便.

You don't "need" it. But defining it allows your object to be implicitly converted to string, which is convenient.

具有直接echo的成员函数被认为是不良形式,因为它对类本身的输出进行了过多的控制.您想从成员函数返回字符串,并让调用者决定如何处理它们:是将它们存储在变量中,还是将它们存储为echo,等等.使用magic函数意味着您不需要显式函数调用即可执行此操作.

Having member functions that echo directly is considered poor form because it gives too much control of the output to the class itself. You want to return strings from member functions, and let the caller decide what to do with them: whether to store them in a variable, or echo them out, or whatever. Using the magic function means you don't need the explicit function call to do this.

这篇关于为什么在PHP的何处以及为什么使用__toString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆