Magic methods in PHP – Part 2
- 2021年3月22日
- 技術情報
I will continue to talk about magic methods article I wrote last week. For the part 1, you can read here.
ToString
The magic __toString () method allows you to define what you would like to display when an object of the class is treated as a string. If you use echo or print on your object, and you haven’t defined the __toString () method, it will give an error.
<?php
class Student {
private $name;
public function __construct($name)
{
$this->name = $name;
$this->email = $email;
}
public function __toString()
{
return 'Name: '.$this->name;
}
}
$student = new Student('Yuuma');
echo $student;
?>
Call
If the __get () and __set () methods are called for non-existent properties, the __call () method is called when trying to invoke inaccessible methods, the methods that have not been defined in your class.
<?php
class Student {
public function __call($methodName, $arg)
{
// $methodName = getName
// $arg = array('1')
}
}
$student = new Student();
$student->getName(1);
?>
Isset
The magic __isset () method is called when you call the isset () method on inaccessible or non-existent object properties. Let’s see how it works with an example.
<?php
class Student {
private $data = array();
public function __isset($name)
{
return isset($this->data[$name]);
}
}
$student = new Student();
echo isset($student->email);
?>
Invoke
The magic __invoke () method is a special method that is called when you try to call an object as if it were a function. the $student object is treated as if it were a function, and since we have defined the __invoke () method, it will be called instead of giving you an error. The main purpose of the __invoke () method is that if you want to treat your objects as callable, you can implement this method.
<?php
class Student {
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function __invoke()
{
echo 'Invoke function';
}
}
$student = new Student('John');
$student();
?>
There are still some magic methods in PHP but let me stop here as I had written most used methods in article part 1 and part 2. If you are interest for more, you can check it out in PHP official documentation.
Yuuma
yuuma at 2021年03月22日 11:00:59