下面这段另类的写法是为了啥
下面这段写法中,问题一:构造函数里面竞然是空的,并且更另类的是他的下面竟然是实例化,如果构造函数是空的,下面如何实例化呢
道理是啥?
<?php<br />/**<br /> * 模板驱动<br /> *<br /> * 模板驱动,商城模板引擎<br /> *<br /> *<br /> * @package tpl<br /> * @copyright Copyright (c) 2007-2013 ShopNC Inc. (http://www.shopnc.net)<br /> * @license http://www.shopnc.net<br /> * @link http://www.shopnc.net<br /> * @author ShopNC Team<br /> * @since File available since Release v1.1<br /> */<br />defined('InShopNC') or exit('Access Invalid!');<br />class Tpl{<br /> /**<br /> * 单件对象<br /> */<br /> private static $instance = null;<br /> /**<br /> * 输出模板内容的数组,其他的变量不允许从程序中直接输出到模板<br /> */<br /> private static $output_value = array();<br /> /**<br /> * 模板路径设置<br /> */<br /> private static $tpl_dir='';<br /> /**<br /> * 默认layout<br /> */<br /> private static $layout_file = 'layout';<br /> <br /> private function __construct(){}<br /> <br /> /**<br /> * 实例化<br /> *<br /> * @return obj<br /> */<br /> public static function getInstance(){<br /> if (self::$instance === null || !(self::$instance instanceof Tpl)){<br /> self::$instance = new Tpl();<br /> }<br /> return self::$instance;<br /> }<br /> <br /> /**<br /> * 设置模板目录<br /> *<br /> * @param string $dir<br /> * @return bool<br /> */<br /> public static function setDir($dir){<br /> self::$tpl_dir = $dir;<br /> return true;<br /> }<br /> /**<br /> * 设置布局<br /> *<br /> * @param string $layout<br /> * @return bool<br /> */<br /> public static function setLayout($layout){<br /> self::$layout_file = $layout;<br /> return true;<br /> }<br /> <br /> /**<br /> * 抛出变量<br /> *<br /> * @param mixed $output<br /> * @param void<br /> */<br /> public static function output($output,$input=''){<br /> self::getInstance();<br /> <br /> self::$output_value[$output] = $input;<br /> }<br /> <br /> /**<br /> * 调用显示模板<br /> *<br /> * @param string $page_name<br /> * @param string $layout<br /> * @param int $time<br /> */<br /> public static function showpage($page_name='',$layout='',$time=2000){<br /> if (!defined('TPL_NAME')) define('TPL_NAME','default');<br /> self::getInstance();<br /> if (!empty(self::$tpl_dir)){<br /> $tpl_dir = self::$tpl_dir.DS;<br /> }<br /> //默认是带有布局文件<br /> if (empty($layout)){<br /> $layout = 'layout'.DS.self::$layout_file.'.php';<br /> }else {<br /> $layout = 'layout'.DS.$layout.'.php';<br /> }<br /> $layout_file = BASE_PATH.'/templates/'.TPL_NAME.DS.$layout;<br /> $tpl_file = BASE_PATH.'/templates/'.TPL_NAME.DS.$tpl_dir.$page_name.'.php';<br /> if (file_exists($tpl_file)){<br /> //对模板变量进行赋值<br /> $output = self::$output_value;<br /> //页头<br /> $output['html_title'] = $output['html_title']!='' ? $output['html_title'] :$GLOBALS['setting_config']['site_name'];<br /> $output['seo_keywords'] = $output['seo_keywords']!='' ? $output['seo_keywords'] :$GLOBALS['setting_config']['site_name'];<br /> $output['seo_description'] = $output['seo_description']!='' ? $output['seo_description'] :$GLOBALS['setting_config']['site_name'];<br /> $output['ref_url'] = getReferer();<br /><br /> Language::read('common');<br /> $lang = Language::getLangContent();<br /><br /> @header("Content-type: text/html; charset=".CHARSET);<br /> //判断是否使用布局方式输出模板,如果是,那么包含布局文件,并且在布局文件中包含模板文件<br /> if ($layout != ''){<br /> if (file_exists($layout_file)){<br /> include_once($layout_file);<br /> }else {<br /> $error = 'Tpl ERROR:'.'templates'.DS.$layout.' is not exists';<br /> throw_exception($error);<br /> }<br /> }else {<br /> include_once($tpl_file);<br /> }<br /> }else {<br /> $error = 'Tpl ERROR:'.'templates'.DS.$tpl_dir.$page_name.'.php'.' is not exists';<br /> throw_exception($error);<br /> }<br /> }<br /> /**<br /> * 显示页面Trace信息<br /> *<br /> * @return array<br /> */<br /> public static function showTrace(){<br /> $trace = array();<br /> //当前页面<br /> $trace[Language::get('nc_debug_current_page')] = $_SERVER['REQUEST_URI'].'<br>';<br /> //请求时间<br /> $trace[Language::get('nc_debug_request_time')] = date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']).'<br>';<br /> //系统运行时间<br /> $query_time = number_format((microtime(true)-StartTime),3).'s';<br /> $trace[Language::get('nc_debug_execution_time')] = $query_time.'<br>';<br /> //内存<br /> $trace[Language::get('nc_debug_memory_consumption')] = number_format(memory_get_usage()/1024/1024,2).'MB'.'<br>';<br /> //请求方法<br /> $trace[Language::get('nc_debug_request_method')] = $_SERVER['REQUEST_METHOD'].'<br>';<br /> //通信协议<br /> $trace[Language::get('nc_debug_communication_protocol')] = $_SERVER['SERVER_PROTOCOL'].'<br>';<br /> //用户代理<br /> $trace[Language::get('nc_debug_user_agent')] = $_SERVER['HTTP_USER_AGENT'].'<br>';<br /> //会话ID<br /> $trace[Language::get('nc_debug_session_id')] = session_id().'<br>';<br /> //执行日志<br /> $log = Log::read();<br /> $trace[Language::get('nc_debug_logging')] = count($log)?count($log).Language::get('nc_debug_logging_1').'<br/>'.implode('<br/>',$log):Language::get('nc_debug_logging_2');<br /> $trace[Language::get('nc_debug_logging')] = $trace[Language::get('nc_debug_logging')].'<br>';<br /> //文件加载<br /> $files = get_included_files();<br /> $trace[Language::get('nc_debug_load_files')] = count($files).str_replace("\n",'<br/>',substr(substr(print_r($files,true),7),0,-2)).'<br>';<br /> return $trace;<br /> }<br />}<br />
------解决思路----------------------
这种写法是单例模式。
单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
http://baike.baidu.com/view/1859857.htm
------解决思路----------------------
构造函数是否为空,和实例化没有关系
构造函数为空,只不过表示实例化时没有用户自定义动作。并且也不执行父类(如果有的话)的构造函数
private function __construct(){}
表示该类不能在外部实例化,私有方法只能在定义它的类里面访问
在类外面 new Tpl
将会有一个 Call to private Tpl::__construct() from invalid context 的致命错误
这是单例模式的写法,但少了
private function __clone(){}
如果单例模式的对象能被克隆的话,就违背了单例的初衷
对于你的这个类,单不单例已经没有意义了,因为他所有的属性和方法都是静态的
因为静态的属性是在各实例间共享的

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
