本文是一個系列的第一篇,目前想到的其他一些主題是:
SQL注入問題
事件模型
AOP模型
UI Framework的實現(xiàn)
Template機制
PHP沉思錄
工作模型
PHP的工作模型非常特殊。從某種程度上說,PHP和ASP、ASP.NET、JSP/Servlet等流行的Web技術(shù),有著本質(zhì)上的區(qū)別。
以Java為例,Java在Web應用領(lǐng)域,有兩種技術(shù):Java Servlet和JSP(Java Server Page)。Java Servlet是一種特殊類型的Java程序,它通過實現(xiàn)相關(guān)接口,處理Web服務器發(fā)送過來的請求,完成相應的工作。JSP在形式上是一種類似于PHP 的腳本,但是事實上,它最后也被編譯成Servlet。
也就是說,在Java解決方案中,JSP和Servlet是作為獨立的Java應用程序執(zhí)行的,它們在初始化之后就駐留內(nèi)存,通過特定的接口和 Web服務器通信,完成相應工作。除非被顯式地重啟,否則它們不會終止。因此,可以在JSP和Servlet中使用各種緩存技術(shù),例如數(shù)據(jù)庫連接池。
ASP.NET的機制與此類似。至于ASP,雖然也是一種解釋型語言,但是仍然提供了Application對象來存放應用程序級的全局變量,它依托于ASP解釋器在IIS中駐留的進程,在整個應用程序的生命期有效。
PHP卻完全不是這樣。作為一種純解釋型語言,PHP腳本在每次被解釋時進行初始化,在解釋完畢后終止運行。這種運行是互相獨立的,每一次請求都會創(chuàng)建一個單獨的進程或線程,來解釋相應的頁面文件。頁面創(chuàng)建的變量和其他對象,都只在當前的頁面內(nèi)部可見,無法跨越頁面訪問舊電腦回收。
在終止運行后,頁面中申請的、沒有被代碼顯式釋放的外部資源,包括內(nèi)存、數(shù)據(jù)庫連接、文件句柄、Socket連接等,都會被強行釋放。
也就是說,PHP無法在語言級別直接訪問跨越頁面的變量,也無法創(chuàng)建駐留內(nèi)存的對象。見下例:
class StaticVarTester {
public static $StaticVar = 0;
}
function TestStaticVar() {
StaticVarTester :: $StaticVar += 1;
echo "StaticVarTester :: StaticVar = " . StaticVarTester :: $StaticVar;
}
TestStaticVar();
echo "
";
TestStaticVar();
?>
在這個例子中,定義了一個名為StaticVarTester的類,它僅有一個公共的靜態(tài)成員$StaticVar,并被初始化為0。然后,在 TestStaticVar()函數(shù)中,對StaticVarTester :: $StaticVar進行累加操作,并將它打印輸出。
熟悉Java或C++的開發(fā)者對這個例子應該并不陌生。$StaticVar作為StaticVarTester類的一個靜態(tài)成員,只在類被裝載時進行初始化,無論StaticVarTester類被實例化多少次,$StaticVar都只存在一個實例,而且不會被多次初始化。因此,當?shù)谝淮握{(diào)用 TestStaticVar()函數(shù)時,$StaticVar進行了累加操作,值為1,并被保存。第二次調(diào)用TestStaticVar()函數(shù),$ StaticVar的值為2。
打印出來的結(jié)果和我們預料的一樣:
StaticVarTester :: StaticVar = 1
StaticVarTester :: StaticVar = 2
但是,當瀏覽器刷新頁面,再次執(zhí)行這段代碼時,不同的情況出現(xiàn)了。在Java或C++里面,$StaticVar的值會被保存并一直累加下去,我們將會看到如下的結(jié)果:
StaticVarTester :: StaticVar = 3
StaticVarTester :: StaticVar = 4
…
但是在PHP中,由于上文敘及的機制,當前頁面每次都解釋時,都會執(zhí)行一次程序初始化和終止的過程。也就是說,每次訪問時,StaticVarTester都會被重新裝載,而下列這行語句
public static $StaticVar = 0;
也會被重復執(zhí)行。當頁面執(zhí)行完成后,所有的內(nèi)存空間都會被回收,$StaticVar這個變量(連同整個StaticVarTester類)也就不復存在。

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.
