Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我们在哪里以及为什么在PHP中使用_toString()?_Php_Oop_Tostring - Fatal编程技术网

我们在哪里以及为什么在PHP中使用_toString()?

我们在哪里以及为什么在PHP中使用_toString()?,php,oop,tostring,Php,Oop,Tostring,我理解它是如何工作的,但我们为什么要实际使用它呢 <?php class cat { public function __toString() { return "This is a cat\n"; } } $toby = new cat; print $toby; ?> 这不是和这个一样吗: <?php class cat { public function

我理解它是如何工作的,但我们为什么要实际使用它呢

<?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();
?>

我们不能使用任何其他公共方法来输出任何文本吗?
为什么我们需要这样一个神奇的方法?

使用
\uu toString()
覆盖打印该类对象时调用的运算符,因此,您可以更轻松地配置该类对象的显示方式。

\u toString
允许您在对象转换为字符串时定义输出。这意味着您可以打印对象本身,而不是函数的返回值。这通常更方便。看

_u_toString方法允许类决定当它被视为字符串时将如何反应


这只是一种标准化的方法,用于生成对象的字符串表示形式。如果您假设程序中的所有对象都使用相同的方法,那么您的
random\u方法
就可以工作,如果您使用第三方库,情况可能就不一样了

您不需要magic方法,但它提供了方便,因为您永远不需要显式地调用它

此外,如果PHP在内部希望将对象转换为文本,它知道如何做到这一点。

您不需要它。但定义它允许将对象隐式转换为字符串,这很方便


直接使用
echo
的成员函数被认为是糟糕的形式,因为它给类本身的输出提供了太多的控制。您希望从成员函数返回字符串,并让调用者决定如何处理它们:是将它们存储在变量中,还是将它们回送出去,或者其他什么。使用magic函数意味着您不需要显式函数调用来完成此操作。

您不必专门调用toString方法。当您打印对象时,字符串被隐式调用。任何其他方法都必须显式调用。

\uuuu toString()
当对象传递给函数(esp
echo()
print()
)时,当其上下文预期为字符串时,调用该方法。由于对象不是字符串,因此
\uu toString()
处理将对象转换为某种字符串表示形式的过程。

除了所有现有答案之外,下面是一个示例:

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();
类别资产{
受保护的
$queue=array();
公共函数添加($script){
$this->queue[]=$script;
}
公共函数uuToString(){
$output='';
foreach($this->queue as$script){
$output.='';
}    
返回$output;
}
}
$scripts=新资产();
它是一个帮助您管理Java脚本的简单类。您可以通过调用
$scripts->add(“…”)
来注册新脚本

然后,要处理队列并打印所有注册的脚本,只需调用
print$scripts

显然,这个类在这个表单中是没有意义的,但是如果您实现了资产依赖、版本控制、检查重复包含等,它就开始有意义了()

基本思想是,这个对象的主要目的是创建一个字符串(HTML),因此在本例中使用uu-toString很方便…

就像用c覆盖一样:


__字符串帮助我们在构造函数中出现错误时返回错误消息

下面的伪代码将更好地说明这一点。在此,如果对象创建失败,将发送错误字符串:

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

没有任何运算符重载/重写。每当对象转换为字符串时,就会调用该方法。这是一个php问题。这有什么帮助??您如何调用此方法将它们存储在变量中。如果您有一个名为StringClass的类,您可以这样做吗<代码>$stringClass=新stringClass()$string=(string)$stringClass
。正如只分配
$string=$stringClass
会分配对象一样。@SamBremner:这看起来是显式触发转换的合理方式(试试看会发生什么!)。但真正的功能在于隐式转换,否则您也可以创建自己的
toString()
函数,或者使用任何其他名称创建类似的函数)。
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