Where and why do we use __toString() in PHP?

2019-04-18 06:41发布

问题:

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?

回答1:

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.



回答2:

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('...').

Then to process the queue and print all registered scripts simply call 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...



回答3:

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.

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.



回答4:

__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.



回答5:

The __toString method allows a class to decide how it will react when it is treated like a string

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



回答6:

__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.



回答7:

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.



回答8:

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.



回答9:

it's like override with 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 oop tostring