Core\Sse\Message::value
$message->value(): mixedReturns the value that was published to the topic.
A publisher calls Core\Topic::publish with a topic and a value. Every stream that subscribed to that topic receives the value as a Core\Sse\Message, and value() returns it. Its type is mixed, so the program converts it before it uses it, for example with as string or as ?int.
The value is a copy. If the program changes it, the publisher and the other streams do not see the change. A value that was tainted when it was published is still tainted when it arrives.
The examples below print a published text, check whether a value is a number, and add up ticket sales for a live counter.
Return value
Returns mixed. The published value. If it was tainted, it is still tainted. It is a copy, so a change to it does not change anything the publisher sees.
Examples
The published text
<?nvs// Shows how to read the value that was published.
// The `.nvse` file beside this example publishes one value on `chat`.Core\Sse $sse = Core\Sse::current();Core\Topic::subscribe('chat');
?Core\Sse\Message $message = $sse->receive();if ($message != null) { // `value()` returns what the publisher sent, as a `mixed` value. `as string` converts // it to a `tainted string`. This prints `anna: Hello, everyone!`. tainted string $text = $message->value() as string; echo $text, "\n";}anna: Hello, everyone!A value that is not a number
<?nvs// Shows how to check a value before the program uses it as a number.
// The `.nvse` file beside this example publishes `5` and then `many` on `queue`.Core\Sse $sse = Core\Sse::current();Core\Topic::subscribe('queue');
?Core\Sse\Message $message = $sse->receive();while ($message != null) { // `as ?int` converts the value to a whole number. For `many` that is not // possible, so the result is `null`. This prints `5 jobs` and then `not a number`. ?int $waiting = $message->value() as ?int; if ($waiting == null) { echo "not a number\n"; } else { echo $waiting, " jobs\n"; } $message = $sse->receive();}5 jobsnot a numberA live ticket counter
<?nvs// Shows a live counter for a concert's ticket page. Each sale publishes how many// tickets were sold, and the stream sends the new total to the page.
// The `.nvse` file beside this example publishes three sales on `sales`.Core\Sse $sse = Core\Sse::current();Core\Topic::subscribe('sales');
int $sold = 0;?Core\Sse\Message $message = $sse->receive();while ($message != null) { ?int $tickets = $message->value() as ?int; if ($tickets != null) { $sold = $sold + $tickets; // This prints the totals `2`, `6` and `7`, each as a `sold` event. $sse->send($sold, event: 'sold'); } $message = $sse->receive();}event: solddata: 2
event: solddata: 6
event: solddata: 7