- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我们最近讨论了是否可以构建 trait Singleton
PHP Traits我们尝试了一个可能的实现,但在构建一个时遇到了问题。
这是一个学术练习。我知道 Singletons have very little - if not to say no - use in PHP
那one 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();
Hi!
object(A)#1 (1) {
["foo"]=>
int(1)
}
Fatal error: Call to private A::__construct() from invalid context in ...
关于php - 使用 PHP 5.4 构建单例特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7104957/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!