Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Response->on('end') signature weirdness? #80

Closed
andig opened this issue Apr 4, 2017 · 3 comments
Closed

Response->on('end') signature weirdness? #80

andig opened this issue Apr 4, 2017 · 3 comments
Labels

Comments

@andig
Copy link

andig commented Apr 4, 2017

I've got the following simple code which sends a request and displays the response.

Problem: the echoed buffer will always be string(0) unless I declare it as &buffer in the on('end'). string(0) is how the buffer is initialized:

$request = $client->request(
	'POST',
	$url,
	array(
		'Content-Length' => strlen($data),
		'Content-Type' => 'application/json'
	)
);

$request->on('response', function ($response) {
	$buffer = '';

	$response->on('data', function ($data, $response) use (&$buffer) {
		$buffer .= (string) $data;
	});

	$response->on('end', function ($error) use ($response, $buffer /* < by ref matters */) {
		echo(sprintf("HTTP %d\n", $response->getCode()));
		if ($buffer) {
			echo($buffer . PHP_EOL);
		}
	});
});

$request->end($data);

Might this be a problem with PHP-internal optimization?

@andig andig changed the title Response->on('end') signatur weirdness? Response->on('end') signature weirdness? Apr 4, 2017
@clue
Copy link
Member

clue commented Apr 4, 2017

This sounds like a duplicate of #70? :-) This is something I'm currently working on, so stay tuned 👍

@clue clue added the question label Apr 4, 2017
@clue
Copy link
Member

clue commented Apr 4, 2017

Sorry, misinterpreted your issue.

This is in fact expected behavior, because you would otherwise bind the initial variable value to your closure, but you actually want the value that changes over time (due to your data callback).

I hope this helps 👍

I believe this has been answered, so I'll close this for now. Please feel free to come back with more details if this problem persists and we can reopen this 👍

@clue clue closed this as completed Apr 4, 2017
@andig
Copy link
Author

andig commented Apr 4, 2017

This is in fact expected behavior, because you would otherwise bind the initial variable value to your closure, but you actually want the value that changes over time (due to your data callback).

I was always under the impression that binding by ref is only required for writing back. But your explanation makes much more sense, big thanks for taking the time!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants