How does method chaining work in PHP and what are its benefits?

Method chaining in PHP allows you to call multiple methods on an object in a single line of code by returning the object itself from each method. This can lead to cleaner and more readable code, as well as reducing the need for temporary variables.

class Example {
    private $value;

    public function __construct($value) {
        $this->value = $value;
    }

    public function add($num) {
        $this->value += $num;
        return $this;
    }

    public function multiply($num) {
        $this->value *= $num;
        return $this;
    }
}

$example = new Example(5);
$result = $example->add(3)->multiply(2)->add(10)->multiply(5)->value;
echo $result; // Output: 200