Swoole\Coroutine::getContext(int $cid = 0)

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\Coroutine::getContext(int $cid = 0)

Parameters

cid

Coroutine ID. By default, use the ID of current coroutine.

Return

context

The context of a coroutine

Description

Get the context of a coroutine by coroutine ID.

Example

<?php
function php_object_id($object)
{
    static $id = 0;
    static $map = [];
    $hash = spl_object_hash($object);
    return $map[$hash] ?? ($map[$hash] = ++$id);
}

class Resource
{
    public function __construct()
    {
        echo __CLASS__ . '#' . php_object_id((object)$this) . ' constructed' . PHP_EOL;
    }

    public function __destruct()
    {
        echo __CLASS__ . '#' . php_object_id((object)$this) . ' destructed' . PHP_EOL;
    }
}

Co\run(function () {
    $context = Swoole\Coroutine::getContext();
    $context['resource1'] = new Resource;
    var_dump($context);
});
Last updated on August 31, 2022