Skip to content

Instantly share code, notes, and snippets.

@danielecr
Created August 29, 2019 13:33
Show Gist options
  • Save danielecr/49c35c137c38a9880a84c45f95483642 to your computer and use it in GitHub Desktop.
Save danielecr/49c35c137c38a9880a84c45f95483642 to your computer and use it in GitHub Desktop.
tricky timer in reactphp
<?php
require_once 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$context = new React\ZMQ\Context($loop);
$timer = $loop->addPeriodicTimer(20, function() use($timer) {
global $loop;
echo "is executed\n";
$loop->cancelTimer($timer);
});
$loop->run();
/* it fails with:
Fatal error: Uncaught TypeError: Argument 1 passed to React\EventLoop\ExtUvLoop::cancelTimer() must implement interface React\EventLoop\TimerInterface, null given, called in /home/scroll/code/tests/testTimer.php on line 11 and defined in /home/scroll/code/vendor/react/event-loop/src/ExtUvLoop.php:164
Stack trace:
#0 /..../testTimer.php(11): React\EventLoop\ExtUvLoop->cancelTimer(NULL)
#1 /..../vendor/react/event-loop/src/ExtUvLoop.php(146): {closure}(Object(React\EventLoop\Timer\Timer))
#2 [internal function]: React\EventLoop\ExtUvLoop->React\EventLoop\{closure}(Object(UVTimer))
#3 /..../vendor/react/event-loop/src/ExtUvLoop.php(230): uv_run(Object(UVLoop), 1)
#4 /..../testTimer.php(14): React\EventLoop\ExtUvLoop->run()
#5 {main}
thrown in /..../vendor/react/event-loop/src/ExtUvLoop.php on line 164
/*
<?php
require_once '../vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$context = new React\ZMQ\Context($loop);
$timer = $loop->addPeriodicTimer(20, function() use(&$timer) {
global $loop;
echo "is executed\n";
$loop->cancelTimer($timer);
});
$loop->run();
// it print 'is executed' and exit cleanly
// (it exists because nothing more is attached to the $loop after cancel)
@danielecr
Copy link
Author

use keyword works the same as function parameters: it accepts parameters as value or as reference.
If passed as value, the only value available at that point was null (still uninitialized variable), in fact the $timer is returned by addPeriodicTimer() method after the call.

@danielecr
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment