<?php

class counter {

	private $size;
	public  $a_error;
	public  $o_shm;
	private $count;

	public function __construct() {
		$this->size = 100;
		$this->count = 0;
		$this->a_error = array();
	}

	public function __destruct() {
		if ($this->o_shm) {
			shmop_close($this->o_shm);
		}
	}

	public function count($id) {
		$this->connect($id, 'c');
		$this->count = $this->read();

		$this->count++;
		$this->write($this->count);
	}

	public function connect($id, $flg='c') {
		$this->o_shm = shmop_open($id, $flg, 0644, $this->size);
		if (!$this->o_shm) {
		    $this->_setError('共有メモリセグメントを作成できませんでした。');
		}
	}

	public function is_error() {
		return (count($this->a_error)) ? $this->a_error : FALSE;
	}

	public function read($id='', $flg='') {
		$this->_checkObj($id, $flg);
		return sprintf("%d",shmop_read($this->o_shm, 0, $this->size));
	}

	public function write($data, $id='') {
		$this->_checkObj($id);
		$_len = strlen($data);
		if ($_len > $this->size) {
			$this->_setError('データサイズが大きすぎます。');
			return;
		}

		$new_len = shmop_write($this->o_shm, $data, 0);
		if ($new_len != $_len) {
		    $this->_setError('データ全体を書き込めませんでした。');
		}
	}

	public function getCount() {
		return $this->count;
	}

	private function _checkObj($id) {
		if (!$this->o_shm && $id) {
			$this->connect($id, $flg);
		}
	}

	private function _setError($str) {
		$this->error[] = $str;
	}
}

