Magic Method toString in OOP in PHP
The first magic method we will
study is called __toString
. It is
called when attempting to convert a class instance
to a string. Let's figure out what
this means. Suppose we have the following class
User
:
<?php
class User
{
private $name;
private $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
public function getName()
{
return $this->name;
}
public function getAge()
{
return $this->age;
}
}
?>
Let's create an object of this class:
<?php
$user = new User('john', 25);
?>
Now let's try to output the created object
via echo
:
<?php
$user = new User('john', 25);
echo $user;
?>
Attempting to output an object via echo
is a conversion to a string. In this
case, PHP will throw an error because objects
cannot be converted to a string just like that.
To remove the error, we must
explicitly tell PHP what to do when
attempting to convert an object to a string. This
is what the magic method
__toString
exists for.
If we create such a method in our class code,
then the result of this method (i.e., what
it returns via return
) will be the string
representation of the object.
Suppose we want the user's name
to be displayed when trying to output
the object via echo
. So let's create the method __toString
and return the value of the name
property in it:
<?php
class User
{
private $name;
private $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
// Implement the specified method:
public function __toString()
{
return $this->name;
}
public function getName()
{
return $this->name;
}
public function getAge()
{
return $this->age;
}
}
?>
Let's test:
<?php
$user = new User('john', 25);
echo $user; // will output 'john' - it works!
?>
Create a class User
, in which there will be
properties name
and surn
.
Make it so that when
outputting the object via echo
to the screen,
a string with the user's first and last name is displayed.