最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Singelton class does not work, multiple initialization on page reload

programmeradmin0浏览0评论

I would like to create a class that provides a logging mechanism. For this I have created the following class:

<?php
namespace tfaq;

final class Logger
{
    private static ?Logger $instance = null;
    private static $logfilePath;
    private static $writeCnt = 0;

    public static function getInstance(): Logger
    {
        if (static::$instance === null) {
            static::$instance = new static();

        static::$logfilePath = Init::getInstance()->get_plugin_path() . 'log.txt';

        if (!file_exists(static::$logfilePath)) {
            $log = fopen(static::$logfilePath, "w") or die("Unable to open file!");
            fwrite($log, '');
            fclose($log);
        }

        }

        return static::$instance;
    }

    public function write_log_entry($text) {
        $log = fopen(static::$logfilePath, "a") or die("Unable to open file!");

        if(static::$writeCnt>0) {
            fwrite($log, "\r\n");
        }

        fwrite($log, $text . '[ ' . static::$writeCnt . ' ]');
        fclose($log);

        static::$writeCnt = static::$writeCnt + 1;

    }

}

I use this class on one page:

<?php

use tfaq\Logger;

Logger::getInstance()->write_log_entry('write log entry...');

If I reload this page several times now, I get the following file... I simply cannot explain it to myself. Maybe I am blind or stupid.

First Entry...[ 0 ]First Entry...[ 0 ]First Entry...[ 0 ]
发布评论

评论列表(0)

  1. 暂无评论