如何限制单例类的克隆? - php

我知道如何在php中创建单例类。但是我感到困惑的是,如果我们能够克隆它,那将是该类的浪费。

我可以知道如何限制单例类的克隆吗?请检查以下代码:

class DatabaseConnection {

private static $singleton_instance = null;

private function construct__() {
    // Declaring the constructor as private ensures
    // that this object is not created as a new intance
    // outside of this class.  Therefore you must use the
    // global_instance function to create this object.
}

public static function global_instance() {
    static $singleton_instance = null;
    if($singleton_instance === null) {
        $singleton_instance = new DatabaseConnection();
    }

    return($singleton_instance);
}
}

参考方案

有一个__clone()方法可以帮助您防止克隆。

public function __clone()
{
    trigger_error('Cloning forbidden.', E_USER_ERROR);
}

PHP-将日期插入日期时间字段 - php

我已在数据库中使用datetime字段存储日期,使用PHP将“今天的日期”插入该字段的正确方法是什么?干杯, 参考方案 我认为您可以使用php date()函数

PHP getallheaders替代 - php

我正在尝试从服务器上的apache切换到nginx。唯一的问题是我在PHP脚本中使用的getallheaders()函数,该函数不适用于Nginx。我已经尝试过用户在getallheaders函数上的php站点上提供的注释,但这并不返回所有请求标头。请告诉我如何解决这个问题。我真的想切换到Nginx。 参考方案 您仍然可以使用它,但是您必须像这里一样重新定义…

PHP mysqli获取查询返回的第一行的值 - php

我正在使用mysqli从数据库中获取某些数据。我正在使用的查询已设置为仅从数据库返回一行。有没有一种方法可以在不使用while循环的情况下获取该行的值?我知道一个while循环对于返回多于一行的行很有用,但是如果不需要while循环,我想避免这种情况,因为不必要的代码是不好的编程。 参考方案 是的-您可以使用:$row = $result->fetch…

php Singleton类实例将在多个会话中保留吗? - php

举一个简单的例子,如果我想计算一个不使用磁盘存储的脚本的命中次数,我可以使用静态类成员来执行此操作吗?用户1:<?php $test = Example::singleton(); $test->visits++; ?> 用户2:<?php $test = Example::singleton(); $test->visits+…

更改默认的URL PHP - php

如何更改默认网址。例如www.example.com/index.php-> www.example.com现在,我要将其设置为www.example.com/test.php。我应该在php.ini中进行更改吗? 参考方案 假设您正在使用apache,则可以通过DirectoryIndex指令执行此操作。Check out the docs。