I am reading data from the sheet and want to implement singleton in my process so that I can run read function, one at a time.
I have written a code for the same which calls the class and set a static variable and then call the function to check if it has the class, so if the class is there then don't run the read function.
class DataParser extends config {
private static $_instance = false;
public static
function getInstance() {
if (self::$_instance == false) {
print_r("expression");
self::$_instance = true;
return self::$_instance;
}
return false;
}
function __construct($params) {}
}
$dataParser = new DataParser($confData);
$p = DataParser::getInstance();
if ($p) {
$res = $dataParser - > read();
}
I want to run the read function one at a time, if one read is running then the other read will not run.
A singleton needs to prevent public constructing and cloning. This can simply be achieved by declaring these methods as protected
.
To check if read()
is currently being executed, you can use a flag $isRunning
.
<?php
class DataParser
{
protected static $instance;
protected static $isRunning = false;
protected function __construct()
{
}
protected function __clone()
{
}
public static function getInstance(): DataParser
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function read(): void
{
if (static::$isRunning) {
throw new RuntimeException('DataParse is already running');
}
static::$isRunning = true;
// Do some reading
static::$isRunning = false;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.