PHP/Class/ toString

Материал из Web эксперт
Перейти к: навигация, поиск

Defining a class"s stringification

 
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>";
    }
}



__toString( ) set a string value for the object that will be used if the object is ever used as a string.

 
<?
    class Cat {
            public function _ _toString( ) {
                    return "This is a cat\n";
            }
    }
    $toby = new Cat;
    print $toby;
?>



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