PHP/Class/ toString
Defining a class"s stringification
<source lang="html4strict">
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>"; }
}
</source>
__toString( ) set a string value for the object that will be used if the object is ever used as a string.
<source lang="html4strict">
<?
class Cat { public function _ _toString( ) { return "This is a cat\n"; } } $toby = new Cat; print $toby;
?>
</source>
Using the __toString() Method
<source lang="html4strict">
<?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;
?>
</source>