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);
}
}
?>
允许类实例的一个单独接口被重新获得。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.
?>
$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.
?>
我在乡下当农民,又学英语又耕地方,某天学会ABC,就能开拖拉机.