我正在更新已实现单例模式的类的私有属性,我在一个类的一个函数中更改其值,但在其他函数中更改其值没有改变。这是我的班级:
class notifications
{
private static $contacts = array(
"+11112223333" => array(
"status" => "pending"
),
"+14445556666" => array(
"status" => "pending"
)
);
private $next = false;
private $log;
// Singleton instance
private static $instance;
private function __construct()
{
$this->log = fopen("log.txt", "a+") or die("Unable to open file!");
}
// getInstance method
public static function getInstance()
{
if(!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
// Send Notification via Call
public function notifyCall($message)
{
$client = new Services_Twilio($this->account_sid, $this->auth_token);
try {
$keys = array_keys(notifications::$contacts);
foreach ($keys as $key) {
fwrite($this->log, "sending notification to ".$key."\n");
// Sending call logic here
$this->next = false;
while(!$this->next) {
echo $this->next;
if($this->next === -1)
die;
}
}
}
catch(Exception $e) {
fwrite($this->log, $e->getMessage());
throw new Exception($e->getMessage());
}
fclose($this->log);
http_response_code(200);
}
// Set status for call
public function setStatus($recipient, $status)
{
$recipient = str_replace(" ", "+", $recipient);
$file = fopen("status.txt", "a+");
fwrite($file, $recipient." : ".$status."\n");
$keys = array_keys(notifications::$contacts);
notifications::$contacts[$recipient]["status"] = $status;
if(notifications::$contacts[$recipient]["status"] === "in-progress") {
fwrite($this->log, "notifying next contact");
$this->next = -1;
}
else if(notifications::$contacts[$recipient]["status"] === "busy" || notifications::$contacts[$recipient]["status"] === "no-answer") {
fwrite($this->log, "Next!");
$this->next = true;
}
foreach ($keys as $key) {
echo "$key: ".notifications::$contacts[$key]['status']."\n";
}
fclose($file);
}
}
以下是我如何使用此课程
require_once("notifications.php");
$recipient = $_POST["To"];
$status = $_POST["CallStatus"];
$notification = notifications::getInstance();
$notification->setStatus($recipient, $status);
请注意,类和状态更新都在单独的文件中,并且它们具有不同的URL,但联系人及其状态在两个文件之间共享
我在日志文件中输出的是它开始向第一个联系人发送呼叫并且状态也被接收并记录在setStatus
函数中,并且next
打印在日志文件中但是在sendNotificationCall
函数上,它实际上并不是在循环时结束,也不是向下一个联系人发送通知。
任何人都可以指导我这里错了吗?我也尝试将$next
设为static
$contacts
,但效果并不好,所以我对这个错误感到困惑。