Please tell me how to implement a similar method call for an object:

$request = $request ->withMethod('OPTIONS') ->withRequestTarget('*') ->withUri(new Uri('https://example.org/')); 

Should each function return an object instance of a class? PS I met a similar implementation in Yii2.

  • Well, yes, you return the object itself in the method and that’s all, but this is better done only with definitely targeted objects. Where is the most convenient to make лапшу - Vasily Barbashev

1 answer 1

What you cite as an example is often called the Fluent Interface design pattern. The implementation is trivial: you need to return $this from methods that change the internal state of the object. For example:

 class Human { private $firstName = ''; private $lastName = ''; public function setFirstName($first_name) { $this->firstName = $first_name; retrun $this; } public function setLastName($last_name) { $this->lastName = $last_name; retrun $this; } public function getFullName() { retrun $this->first_name . ' ' . $this->last_name; } } $john = new Human(); $john->setFirstName('John') ->setLastName('Doe') ->getFullName(); // 'John Doe'