2009-10-16 124 views
1

有没有办法在PHP脚本中阻止同一个类的实例?一个类实例

$user = new User(); 


$user2 = new User(); // I want to catch another instance of the user class and throw an exception 

我试图创建一个静态变量和一个静态函数操纵它:

User::instance() 

但不会做阻止我:

$user = new User(); 
+2

我不同意@Tordek,我觉得单身是非常有用的,当他们使用righr方式 – Tech4Wilco 2011-09-16 17:43:25

回答

2
<?php 
class Foo { 
    static function instance() { 
    static $inst = null; 
    if ($inst === null) { $inst = new self; } 
    return $inst; 
    } 
    private function __construct() { } 
    private function __clone() { } 
} 
+0

是这样的同样做单身的方式? – yretuta 2009-10-16 00:42:08

+0

这是一个单身人士。 – 2009-10-16 01:03:18

+0

我只是修复了一个错误btw。 – 2009-10-16 01:04:30

1

这已经有一段时间,因为我已经试过这样做,但你尝试过让你的__construct法保护的或私有?

0

我不知道关于PHP语法和语言特性,但你可以在你的类User类型的静态字段,将让您User对象的实例。并让构造函数抛出一个错误。这样,当你想要一个你的班级的实例时,你可以调用User.Instance并且这将返回唯一存在的实例。如果您尝试实例化对象,则会引发错误。

在C#中,它看起来像这样。正如我所提到的,我不知道PHP的语法。

class User 
{ 
    private static User instance = null; 

    public User() 
    { 
     //throw exception 
    } 

    public static User Instance 
    { 
    get 
    { 
     if(instance == null) 
     { 
      instance = new User(); 
     } 
     return instance; 
    } 
    } 

} 
6

不改变对象的语义,你可以在构造函数中保留一个静态计数器。这不是一个单身,因为它不是全局可用,仅仅只有一次实例化的...

class Foo { 
    private static $counter = 0; 
    final public function __construct() { 
     if (self::$counter) { 
      throw new Exception('Cannot be instantiated more than once'); 
     } 
     self::$counter++; 
     // Rest of your constructor code goes here 
    } 
    // Rest of class 
} 
+1

羽绒选民:谨慎解释?它回答了OP要求的内容。它不会增加新的副作用(就像单身人士一样,引入对象的全局可用性),它仍然解决了OP要求的内容。所以真的,这是唯一的答案,实际上回答这个问题,而不添加新的假设... – ircmaxell 2012-03-23 12:43:31