我们在哪里以及为什么在 PHP 中使用 __toString() ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5172261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where and why do we use __toString() in PHP?
提问by Stann
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;
?>
Isn't this the same as this:
这不是和这个一样吗:
<?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?
我们不能只使用任何其他公共方法来输出任何文本吗?为什么我们需要这样的魔法方法?
采纳答案by Lightness Races in Orbit
You don't "need" it. But defining it allows your object to be implicitly converted to string, which is convenient.
你并不“需要”它。但是定义它可以让您的对象隐式转换为字符串,这很方便。
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.
拥有echo
直接的成员函数被认为是糟糕的形式,因为它给类本身的输出提供了太多的控制。您想从成员函数中返回字符串,并让调用者决定如何处理它们:是将它们存储在变量中,还是将echo
它们取出,或者其他什么。使用魔术函数意味着您不需要显式函数调用来执行此操作。
回答by nice ass
In addition to all existing answers, here's an example, :
除了所有现有的答案,这里有一个例子,:
class Assets{
protected
$queue = array();
public function add($script){
$this->queue[] = $script;
}
public function __toString(){
$output = '';
foreach($this->queue as $script){
$output .= '<script src="'.$script.'"></script>';
}
return $output;
}
}
$scripts = new Assets();
It's a simple class that helps you manage javascripts. You would register new scripts by calling $scripts->add('...')
.
这是一个简单的类,可帮助您管理 javascript。您将通过调用注册新脚本$scripts->add('...')
。
Then to process the queue and print all registered scripts simply call print $scripts;
.
然后处理队列并打印所有注册的脚本,只需调用print $scripts;
.
Obviously this class is pointless in this form, but if you implement asset dependency, versioning, checks for duplicate inclusions etc., it starts to make sense (example).
显然这个类在这种形式下是没有意义的,但是如果你实现资产依赖、版本控制、检查重复包含等,它开始变得有意义(示例)。
The basic idea is that the main purpose of this object is to create a string (HTML), so the use of __toString in this case is convenient...
基本思想是这个对象的主要目的是创建一个字符串(HTML),所以在这种情况下使用__toString是方便的......
回答by falstro
It's just a standardized method to produce a string representation of an object. Your random_method
approach works if you assume all objects in your program uses that same method, which might not be the case if you use third party libraries.
它只是一种生成对象字符串表示的标准化方法。你random_method
如果假设所有的对象方法适用于你的程序使用同样的方法,如果使用第三方库可能并非如此。
You don't need the magic method, but it provides convenience, as you'll never really have to call it explicitly.
您不需要魔术方法,但它提供了便利,因为您永远不必显式调用它。
Also, if PHP should internally ever want to turn your object into text, it knows how to do that.
此外,如果 PHP 在内部想要将您的对象转换为文本,它知道如何做到这一点。
回答by Michael Berkowski
__toString()
is called when an object is passed to a function (esp echo()
or print()
) when its context is expected to be a string. Since an object is not a string, the __toString()
handles the transformation of the object into some string representation.
__toString()
当一个对象被传递给一个函数(especho()
或print()
)时,当它的上下文应该是一个字符串时调用。由于对象不是字符串,因此__toString()
处理对象到某种字符串表示的转换。
回答by John Giotta
The __toString method allows a class to decide how it will react when it is treated like a string
__toString 方法允许一个类决定当它被当作一个字符串时它将如何反应
http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring
http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring
回答by lonesomeday
__toString
allows you to define the output when your object is converted to a string. This means that you can print
the object itself, rather than the return value of a function. This is frequently more convenient. See the manual entry.
__toString
允许您定义对象转换为字符串时的输出。这意味着您可以print
使用对象本身,而不是函数的返回值。这通常更方便。请参阅手册条目。
回答by aysuhi
__String helps us it returning error message in case there is some error in constructor.
__String 帮助我们在构造函数中出现错误时返回错误消息。
Following dummy code will clarify it better. Here if creation of object is failed, an error string is sent:
以下虚拟代码将更好地阐明它。如果创建对象失败,则会发送错误字符串:
class Human{
private $fatherHuman;
private $errorMessage ="";
function __construct($father){
$errorMessage = $this->fatherHuman($father);
}
function fatherHuman($father){
if($father qualified to be father){
$fatherHuman = $father;
return "Object Created";//You can have more detailed string info on the created object like "This guy is son of $fatherHuman->name"
} else {
return "DNA failed to match :P";
}
}
}
function run(){
if(ctype_alpha($Rahul = Human(KingKong)){
echo $Rahul;
}
}
run(); // displays DNA failed to match :P
回答by Dan
Using __toString()
overrides the operator that is called when you print objects of that class, so it makes it easier for you to configure how an object of that class should be displayed.
使用__toString()
会覆盖打印该类的对象时调用的运算符,因此您可以更轻松地配置该类的对象的显示方式。
回答by Dennis Traub
You don't have to specifically call the toString method. When ever you print the object toString is being called implicitly. Any other method would have to be called explicitly.
您不必专门调用 toString 方法。当你打印对象 toString 被隐式调用时。任何其他方法都必须显式调用。
回答by FAREH
it's like override with c# :
这就像用 c# 覆盖:
class Person
{
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return FirstName + “ “ + LastName;
}
}