PHP Classes and Objects Defining Object Stringification - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Classes and Objects Defining Object Stringification - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Saturday, May 25, 2019

PHP Classes and Objects Defining Object Stringification

PHP Classes and Objects




Defining Object Stringification

Problem

You want to control how PHP displays an object when you print it.

Solution

Implement a __toString() method:

          class Person {
                  // Rest of class here

                  public function __toString() {
                         return "$this->name <$this->email>";
                  }
          }

Discussion

PHP provides objects with a way to control how they are converted to strings. This allows you to print an object in a friendly way without resorting to lots of additional code.

PHP calls an object’s __toString() method when you echo or print the object by itself. For example:

          class Person {
                  protected $name;
                  protected $email;

                  public function setName($name) {
                         $this->name = $name;
                  }

                  public function setEmail($email) {
                         $this->email = $email;
                  }

                  public function __toString() {
                         return "$this->name <$this->email>";
                  }
          }

You can write:

          $rasmus = new Person;
          $rasmus->setName('Rasmus Lerdorf');
          $rasmus->setEmail('rasmus@php.net');
          print $rasmus;

          Rasmus Lerdorf <rasmus@php.net>

This causes PHP to invoke the __toString() method behind the scenes and return the stringified version of the object.

Your method must return a string; otherwise, PHP will issue an error. Though this seems obvious, you can sometimes get tripped up by PHP’s auto-casting features, which do not apply here.

For example, it’s easy to treat the string '9' and the integer 9 identically, because PHP generally switches seamlessly between the two depending on context, almost always to the correct result.

However, in this case, you cannot return integers from __toString(). If you suspect you may be in a position to return a nonstring value from this method, consider explicitly casting the results, as shown:

          class TextInput {
                  // Rest of class here

                  public function __toString() {
                         return (string) $this->label;
                  }
          }

By casting $this->label to a string, you don’t need to worry if someone decided to label that text input with a number.

The __toString() feature has a number of limitations prior to PHP 5.2. Therefore, if you’re using __toString() heavily in your code, it’s best to use PHP 5.2 or greater.



No comments:

Post a Comment

Post Top Ad