2024 年 PHP Conference Japan

Volatile 類別

(PECL pthreads >= 3.0.0)

簡介

Volatile 類別是 pthreads v3 的新功能。它的引入是由於 Threaded 類別的 Threaded 成員的新不可變語義。 Volatile 類別使其 Threaded 成員可變,也用於在 Threaded 上下文中儲存 PHP 陣列。

類別概要

class Volatile extends Threaded implements Collectable, Traversable {
/* 繼承的方法 */
公開 Threaded::chunk(整數 $size, 布林值 $preserve): 陣列
公開 Threaded::merge(混合 $from, 布林值 $overwrite = ?): 布林值
公開 Threaded::run():
公開 Threaded::synchronized(閉包 $block, 混合 ...$args): 混合
公開 Threaded::wait(整數 $timeout = ?): 布林值
}

範例

範例 #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
5 年前
<?php

// 僅使用繼承 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