【问题标题】:Where and why do we use __toString() in PHP?我们在哪里以及为什么在 PHP 中使用 __toString()?
【发布时间】:2011-07-07 12:48:59
【问题描述】:

我了解它的工作原理,但我们为什么要实际使用它?

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

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

【问题讨论】:

    标签: php oop tostring


    【解决方案1】:

    使用__toString() 会覆盖在您打印该类的对象时调用的运算符,因此您可以更轻松地配置该类的对象应如何显示。

    【讨论】:

    • 没有任何运算符重载/覆盖。每当对象转换为字符串时,都会调用该方法。
    【解决方案2】:

    __toString 允许您在对象转换为字符串时定义输出。这意味着您可以print 对象本身,而不是函数的返回值。这通常更方便。见the manual entry

    【讨论】:

      【解决方案3】:

      __toString 方法允许一个类决定当它被视为字符串时它会如何反应

      http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring

      【讨论】:

        【解决方案4】:

        这只是一种生成对象字符串表示的标准化方法。如果您假设程序中的所有对象都使用相同的方法,那么您的random_method 方法有效,而如果您使用第三方库,情况可能并非如此。

        您不需要魔法方法,但它提供了便利,因为您永远不必显式调用它。

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

        【讨论】:

          【解决方案5】:

          你并不“需要”它。但是定义它可以让你的对象隐式转换为字符串,这很方便。

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

          【讨论】:

          • 如何调用此方法将它们存储在 var 中。如果您有一个名为 StringClass 的类,您可以这样做吗? $stringClass = new StringClass(); $string = (string) $stringClass 。因为只是分配$string = $stringClass 会分配对象。
          • @SamBremner:作为一种显式触发转换的方式,这看起来很合理(试试看会发生什么!)。但真正的威力在于隐式转换,否则你不妨创建自己的toString() 函数,或任何其他名称的类似函数。
          【解决方案6】:

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

          【讨论】:

            【解决方案7】:

            __toString() 在将对象传递给函数(尤其是 echo()print())时调用,而其上下文应为字符串。由于对象不是字符串,__toString() 将对象转换为某种字符串表示形式。

            【讨论】:

              【解决方案8】:

              除了所有现有的答案,这里有一个例子:

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

              这是一个帮助您管理 javascripts 的简单类。您可以通过调用$scripts-&gt;add('...') 注册新脚本。

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

              显然这个类在这种形式下是没有意义的,但如果你实现资产依赖、版本控制、检查重复包含等,它就开始有意义了 (example)。

              基本思想是这个对象的主要目的是创建一个字符串(HTML),所以这种情况下使用__toString比较方便……

              【讨论】:

                【解决方案9】:

                这就像用 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;
                
                }
                
                }
                

                【讨论】:

                • 这是一个 php 问题。这有什么帮助??
                【解决方案10】:

                __String 帮助我们在构造函数中出现错误时返回错误消息。

                下面的虚拟代码会更好地阐明它。这里如果创建对象失败,则会发送一个错误字符串:

                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
                

                【讨论】:

                  【解决方案11】:

                  __toString 允许您在将对象转换为字符串时定义输出。这意味着您可以打印对象本身,而不是函数的返回值。

                  看看下面的例子:

                  <?php
                  
                  class Student 
                  {
                      protected $name;
                      protected $age;
                  
                  public function getName(){
                      return $this->name;
                  }
                  
                  public function getAge(){
                      return $this->age;
                  }
                  
                  private function setName($name){
                       $this->name = $name;
                  }
                  
                  private function setAge($age){
                      $this->age = $age;
                  }
                  
                  
                  public function __construct($name, $age) {
                      $this->setName($name);
                      $this->setAge($age);
                  }
                  
                  public function __toString(){
                      return "hello ". $this->getName(). " my age is ". $this->getAge();
                  }
                  
                  }
                  
                  $obj = new Student("Sajib", 23);
                  echo $obj;

                  【讨论】:

                    猜你喜欢
                    • 2011-07-04
                    • 2014-06-01
                    • 1970-01-01
                    • 2015-05-30
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2019-05-10
                    • 2017-10-01
                    相关资源
                    最近更新 更多