The __toString() magic method allows to echo out the class as string.

So the question arises here is why you want to echo out class and essentially convert it into a string? Let’s take a look at a couple of examples to understand more about __toString() magic method.

First simple Example

class DevPeel
{
	public function __toString(){
		return 'devpeel';
	}
}

$class = new DevPeel();
echo $class;

It will simply echo out the string devpeel in the output.

Another Example

class User
{
	protected $data = [
		'name'=>'usama munir',
		'email'=>'usama@devpeel.com'
	];

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

	public function toJson(){
		return json_encode($this->data);
	}
}

$user = new User();

echo $user;

In this example, we’re using a simple toJson() method to simply out our data as json and later echoing it out as we’ve using __toString() magic method to achieve this.

Now to enhance this example more, let’s say we’ve a UserController which uses our User model and we can do simply like:

class User
{
	protected $data = [
		'name'=>'usama munir',
		'email'=>'usama@devpeel.com'
	];

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

	public function toJson(){
		return json_encode($this->data);
	}
}

class UserController
{
	public function show(){
		$user = new User();
		return $user;
	}
}

$controller = new UserController();

echo $controller->show();

Another Example (Handling Forms)

class InputField
{
	public function __toString(){
		return '
			<input type="'. $this->attributes['type'] .'"
			name="'.$this->attributes['name'].'"
			>
		';
	}
}

class TextField extends InputField
{
	protected $attributes =[];

	public function setType($type){
		$this->attributes['type'] = $type;
	}

	public function setName($name){
		$this->attributes['name'] = $name;
	}
}

$username = new TextField();
$username->setType('text');
$username->setName('username');
echo $username;

In this example, we’re simply setting name & type of the input field and using the __toString() magic method converting it to the string and gets the following output.

<input type="text"
name="username"
>

Another Example (Combining with other Magic methods to tidy things)

class InputField
{
	public function __toString(){
		return '
			<input type="'. $this->type .'"
			name="'.$this->name.'"
			>
		';
	}

	public function __get($key){
		return $this->attributes[$key] ?? '';
	}
}

class TextField extends InputField
{
	protected $attributes =[];

	public function __set($key,$value){
		$this->attributes[$key] = $value;
	}
}

$username = new TextField();
$username->type= 'text';
$username->name= 'username';
echo $username;

Here you can see, we combined __toString() magic method with get and set respectively hence tidying out our code to some extent.

You may also Like