<?php class Example{ // Hold an instance of the class privatestatic$instance; //A private constructor;prevents direct creation of object privatefunction __construct(){ echo'I am constructed'; } // The singleton method publicstaticfunction singleton(){ if (!isset(self::$instance)) { $c=__CLASS__; self::$instance=new$c; } return self::$instance; } // Example method publicfunction bark() { echo'Woof!'; } // Prevent users to clone the instance publicfunction __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. ?>