在PHP中优化instance使用可以通过以下方式:
class Singleton {
private static $instance;
public static function getInstance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
class LazySingleton {
private static $instance;
public static function getInstance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
class DependencyInjection {
private $instance;
public function __construct(Singleton $instance) {
$this->instance = $instance;
}
}
class SingletonFactory {
public static function createInstance() {
return Singleton::getInstance();
}
}
通过以上方式可以优化PHP中的instance使用,提高代码的性能和可维护性。