Volatile 类

(PECL pthreads >= 3.0.0)

介绍

The Volatile 类是 pthreads v3 中的新功能。它的引入是 Threaded 类成员的新不可变语义的结果。The Volatile 类允许其 Threaded 成员的可变性,也用于在 Threaded 上下文中存储 PHP 数组。

类概要

class Volatile extends Threaded implements Collectable, Traversable {
/* 继承的方法 */
public Threaded::chunk(int $size, bool $preserve): array
public Threaded::extend(string $class): bool
public Threaded::merge(mixed $from, bool $overwrite = ?): bool
public Threaded::synchronized(Closure $block, mixed ...$args): mixed
public Threaded::wait(int $timeout = ?): bool
}

示例

示例 #1 Threaded 的新不可变语义

<?php

class Task extends Threaded
{
public function
__construct()
{
$this->data = new Threaded();

// 尝试覆盖 Threaded 类的 Threaded 属性(无效)
$this->data = new stdClass();
}
}

var_dump((new Task())->data);

上面的示例将输出类似于以下内容

RuntimeException: Threaded members previously set to Threaded objects are immutable, cannot overwrite data in %s:%d

示例 #2 Volatile 用例

<?php

class Task extends Volatile
{
public function
__construct()
{
$this->data = new Threaded();

// 尝试覆盖 Volatile 类的 Threaded 属性(有效)
$this->data = new stdClass();
}
}

var_dump((new Task())->data);

上面的示例将输出类似于以下内容

object(stdClass)#3 (0) {
}
添加笔记

用户贡献笔记 1 笔记

synnus at gmail dot com
4 年前
<?php

// 仅使用 extends volatile 用于使用数组
// 非常好

class libvar extends Volatile
{
private
$_adresse = '127.0.0.1';
private
$_port = 10000;

public
$socket;
public
$list_socket = array();
public
$list_error = array();

public function
__construct(){ }

public function
set_list($val) { $ct = count($this->list_socket); $this->list_socket[ $ct ] = $val; return $ct; }
public function
set_socket($val) { $this->socket = $val; return $this->socket; }
public function
set_error($val) { $this->list_error[ count($this->list_error) ] = $val; }

public function
unset_list($val) { unset($this->list_error[ $val ]); }

public function
get_socketinlist($val) { return $this->list_socket[$val]; }
public function
get_adresse() { return $this->_adresse; }
public function
get_port() { return $this->_port; }
public function
get_socket() { return $this->socket; }
}

?>
To Top