I recently had to use Slim\Http\Message
and Slim\Http\Request
to get the users posted data.
I noticed something in the method withBody()
where it was returning a clone of the object instead of $this
.
This caused me some trouble as I couldn't get my application to work until I assigned $request->withBody(...)
to a variable ($request
) and then carried on using that new variable in my script.
I have a mock example to explain (see comments in the code);
class Request {
protected $body;
public function addBody($body) {
$clone = clone $this;
$clone->body = $body;
return $clone;
}
public function getBody() {
return $this->body;
}
}
$request = new Request;
// this will return NULL
$request->addBody([
'name' => 'john',
'email' => 'john@example.com',
]);
var_dump($request->getBody());
// -----------------------
// but this will return the "body" that was passed in above.
$request = $request->addBody([
'name' => 'john',
'email' => 'john@example.com',
]);
var_dump($request->getBody());
I see what is happening here. But I don't understand why a class would be implemented like this.
What are the benefits? Why restrict a developer in this way?