PHP5单接口实现

<?php
class Example{   
    
// Hold an instance of the class
    private static $instance;
    
//A private constructor;prevents direct creation of object 
    private function __construct(){   
        
echo 'I am constructed';   
    }
    
// The singleton method 
     public static function singleton(){   
        
if (!isset(self::$instance)) {    
             
$c = __CLASS__;
            self
::$instance = new $c;
        }
        
return self::$instance;
    }   
    
// Example method
    public function bark() {   
        
echo 'Woof!';   
    }
    
// Prevent users to clone the instance
    public function __clone(){   
        
trigger_error('Clone is not allowed.',E_USER_ERROR);  
    }
}
?> 
允许类实例的一个单独接口被重新获得。
<?php
$test = new Example; // This would fail because the constructor is private
$test = Example::singleton();// This will always retrieve a single instance of the class
$test->bark();
$test_clone = clone($test); // This will issue an E_USER_ERROR.
?> 
posted @ 2008-05-26 15:08  !星期八  阅读(456)  评论(1编辑  收藏  举报