gpt4 book ai didi

PHP 类引用

转载 作者:行者123 更新时间:2023-12-02 17:49:58 31 4
gpt4 key购买 nike

明确地说,我不想多次实例化同一个类。我只想实例化它一次,并通过一些引用跟踪对该实例所做的任何更改。这可能吗?如果可以,该怎么做?谢谢!

最佳答案

您可以使用 Singleton pattern为了这。 PHP manual有一个很好的例子和描述:

The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance.

类:

<?php
class Example
{
private static $instance;
private function __construct() {
}

public static function singleton() {
if (!isset(self::$instance)) {
echo 'Creating new instance.';
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}

public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}

public function __wakeup() {
trigger_error('Unserializing is not allowed.', E_USER_ERROR);
}
}

用法:

$singleton = Example::singleton();

还值得注意的是 PHP 手册中对单例模式的反对意见:

The Singleton pattern is one of the more controversial patterns. Critics argue that Singletons introduce Global State into an application and tightly couple the Singleton and its consuming classes. This leads to hidden dependencies and unexpected side-effects, which in turn leads to code that is harder to test and maintain.

Critics further argue that it is pointless to use a Singleton in a Shared Nothing Architecture like PHP where objects are unique within the Request only anyways. It is easier and cleaner to create collaborator object graphs by using Builders and Factory patterns once at the beginning of the Request.

Singletons also violate several of the "SOLID" OOP design principles and the Law of Demeter. Singletons cannot be serialized. They cannot be subtyped (before PHP 5.3) and won't be Garbage Collected because of the instance being stored as a static attribute of the Singleton.

另见:Who needs singletons?

关于PHP 类引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9444399/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com