Using the __toString() Method : __toString « Class « PHP






Using the __toString() Method

 
<?php
    class User {
            private $username;
            function __construct($name) {
                    $this->username = $name;
            }
            public function getUserName() {
                    return $this->username;
            }
            function __toString() {
                    return $this->getUserName();
            }
    }
    $user = new User("john");
    echo $user;
?>
  
  








Related examples in the same category

1.__toString( ) set a string value for the object that will be used if the object is ever used as a string.
2.Defining a class's stringification