gpt4 book ai didi

php - 使用 PHP 5.4 构建单例特征

转载 作者:IT王子 更新时间:2023-10-28 23:49:59 26 4
gpt4 key购买 nike

我们最近讨论了是否可以构建 trait Singleton PHP Traits我们尝试了一个可能的实现,但在构建一个时遇到了问题。

这是一个学术练习。我知道 Singletons have very little - if not to say no - use in PHPone should 'just create one'但只是为了探索特征的可能性:

<?php
trait Singleton
{
protected static $instance;
final public static function getInstance()
{
return isset(static::$instance)
? static::$instance
: static::$instance = new static;
}
final private function __construct() {
static::init();
}
protected function init() {}
final private function __wakeup() {}
final private function __clone() {}
}

class A {
use Singleton;
public function __construct() {
echo "Doesn't work out!";
}
}

$a = new A(); // Works fine

转载:http://codepad.viper-7.com/NmP0nZ

问题是:可以在 PHP 中创建 Singleton Trait 吗?

最佳答案

我们找到的快速解决方案(感谢聊天!):

如果特征和类都定义相同的方法,则使用类中的方法

所以 Singleton 特性只有在使用它的类没有定义 __construct()

时才有效

特质:

<?php
trait Singleton
{
protected static $instance;
final public static function getInstance()
{
return isset(static::$instance)
? static::$instance
: static::$instance = new static;
}
final private function __construct() {
$this->init();
}
protected function init() {}
final private function __wakeup() {}
final private function __clone() {}
}

消费类示例:

<?php    
class A {
use Singleton;

protected function init() {
$this->foo = 1;
echo "Hi!\n";
}
}

var_dump(A::getInstance());

new A();

var_dump 现在产生预期的输出:

Hi!
object(A)#1 (1) {
["foo"]=>
int(1)
}

新的失败了:

Fatal error: Call to private A::__construct() from invalid context in ...

Demo

关于php - 使用 PHP 5.4 构建单例特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7104957/

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