安裝教學請參考thread安裝
直接上一段簡單的程式碼
<code><span><?php</span><span><span>class</span><span>test</span><span>extends</span><span>Thread</span> {</span><span>public</span><span><span>function</span><span>__construct</span><span>(<span>$fun</span>)</span> {</span><span>$this</span>->fun=<span>$fun</span>; } <span>public</span><span><span>function</span><span>run</span><span>()</span> {</span><span>$param</span>=<span>$this</span>->fun; <span>$this</span>-><span>$param</span>(); } <span>private</span><span><span>function</span><span>test1</span><span>()</span> {</span><span>echo</span><span>1</span>; <span>echo</span><span>"<br>"</span>; } <span>private</span><span><span>function</span><span>test2</span><span>()</span> {</span> sleep(<span>3</span>); <span>echo</span><span>2</span>; <span>echo</span><span>"<br>"</span>; } <span>private</span><span><span>function</span><span>test3</span><span>()</span> {</span><span>echo</span><span>3</span>; <span>echo</span><span>"<br>"</span>; } } <span>$arr</span>=<span>array</span>(<span>'test1'</span>,<span>'test2'</span>,<span>'test3'</span>); <span>foreach</span> (<span>$arr</span><span>as</span><span>$fun</span>) { <span>$th</span>[]=<span>new</span> test(<span>$fun</span>); } <span>foreach</span> (<span>$th</span><span>as</span><span>$worker</span>) { <span>$worker</span>->start(); } </span></code>
輸出結果是
1
3
2
test 類別繼承thread類,需要實作run方法,start方法會自動開啟一個執行緒來執行run方法裡的程序,thread具體的方法請參考官方手冊
http://php.net/manual/zh/class.thread.php
以上就介紹了php thread擴充的使用,包括了方面的內容,希望對PHP教學有興趣的朋友有幫助。