@pc579 it is called automagically, just like the constructor method in a class is called, or the invoke method in a single action controller.
The code below instatiates a new class, and since we are passing an argument, we need to have a constructor to handle that.
$class = new MyClass('MyFirstClass');
That means that php will look for a method named __construct() and run it. A class doesn't require a constructor, but if you want to set properties when you instansciate your class, then you use one.
The same thing goes for an invokable class, that means that you invoke the class when you instantiate it.
Take this ontroller as an example, it uses both a constructor and an invoke to apply the middleware and return the view.
class BooksCreateController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function __invoke()
{
return view('books.create')
}
}
So back to the __toString() method, it is called when php needs a string, and the class method doesn't return one, that is of course if you have specified the method.
class MyClass
{
protected string $name;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
The class above has two methods, a getter and a setter.
If I do this in my code.
$class = new MyClass();
$class->setName('Tray2');
echo $class->getName();
It will echo Tray2.
Since I only have one method returning somthing, then I can simplify the code by doing this
$class = new MyClass();
$class->setName('Tray2');
echo $class;
If I do as above, php will then try to echo $class this will fail, since it is an object of the type MyClass, but php is smart enough to look for a way to try to convert the $class into a string, and what it looks for is __toString() and since we don't have one, it will fail.
To prevent that from happening, we add that method to our class, then the developer can choose if they want
to use the verbose getter or just use the magic casting the object to a string with __toString()
class MyClass
{
protected string $name;
public function __toString()
{
return $this->getName();
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
So to put it simple, php looks for it when it needs to cast an instance of the class to a string value, and if it exists, it does it automagically, so you as a developer doesn't need to write a getter for a proptery, like in the example above.