大家好,我想出了 shm_get_var() 的一種解決方案
在錯誤時返回 false / 返回布林值 false 變數的問題。
測試腳本
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
echo '<pre>';
echo ini_get('sysvshm.init_mem');
require_once('ClassShmWrapper.php5');
$nKey = ftok(__FILE__,'x');
$myShm = new ClassShmWrapper($nKey);
$myShm->attachToSegment();
$myShm->nVarKey = 1;
if ($myShm->getVarFromSegment()) {
echo "在共享記憶體中找到變數\n";
}
else {
echo "在共享記憶體中找不到變數\n";
}
$myShm->detachFromSegment();
echo "\n傾印 " . '$myShm->mVar' . "\n";
var_dump($myShm->mVar);
?>
用於 shm_ 函數的類別以及用於儲存布林值的類別
<?php
class ClassShmWrapper {
public $nPermissions;
public $nKey;
public $nBytesMemorySize;
public $nShmId;
public $nVarKey;
public $mVar;
public function __construct($nKey,$nBytesMemorySize=50000,$nPermissions=0666) {
$this->nKey = $nKey;
$this->nBytesMemorySize = $nBytesMemorySize;
$this->nPermissions = $nPermissions;
}
public function attachToSegment() {
$this->nShmId = shm_attach($this->nKey,$this->nBytesMemorySize,$this->nPermissions);
}
public function detachFromSegment() {
shm_detach($this->nShmId);
}
public function removeSegment() {
shm_remove($this->nShmId);
}
public function getVarFromSegment() {
$mVar = NULL;
if (($mVar = @shm_get_var($this->nShmId,$this->nVarKey)) !== FALSE) {
$this->mVar = $mVar;
unset($mVar);
if ($this->mVar instanceof ClassShmBooleanWrapper) {
$this->mVar = $this->mVar->bVal;
}
return TRUE;
}
else {
return FALSE;
}
}
public function putVarToSegment() {
if (is_bool($this->mVar)) {
return shm_put_var($this->nShmId,$this->nVarKey,new ClassShmBooleanWrapper($this->mVar));
}
else {
return shm_put_var($this->nShmId,$this->nVarKey,$this->mVar);
}
}
public function removeVarFromSgement() {
shm_remove_var($this->nShmId,$this->nVarKey);
}
} class ClassShmBooleanWrapper {
public $bVal;
public function __construct($bVal) {
$this->bVal = $bVal;
}
} ?>