1. 程式人生 > 程式設計 >php語法技巧程式碼例項

php語法技巧程式碼例項

1. DIRECTORY_SEPARATOR 與 PATH_SEPARATOR

DIRECTORY_SEPARATOR:路徑分隔符,linux上就是‘/'    windows上是‘\'
PATH_SEPARATOR:include多個路徑使用,在windows下,當你要include多個路徑的話,你要用”;”隔開,但在linux下就使用”:”隔開的。

2.set_include_path 與 get_include_path

此方法可以設定檔案的include路徑,設定後,include檔案會先在include_path中查詢,如沒再按設定的路徑查詢。
例如:include目錄下有個router.php與config.php,可以這樣include

set_include_path('include');include('route.php');include('config.php');

另外,此方法可以指定多個include_path,用PATH_SEPARATOR分隔。
例如有 ./a ./b ./c 三目錄,每個目錄下分別有a.php,b.php,c.php,include 3個目錄的檔案

$inc_path = array('a','b','c');
set_include_path(get_include_path().PATH_SEPARATOR.implode(PATH_SEPARATOR,$inc_path));
include('a.php');
include('b.php');
include('c.php');

檢視include_path可以使用 get_include_path()

3.call_user_func 與 call_user_func_array

call_user_func 呼叫使用者自定義方法,第一個引數為要呼叫的方法名,第二個引數開始為呼叫方法要傳遞的引數。

function foo($a,$b){
 echo $a.' '.$b;
}
call_user_func('foo',100,200); // 輸出:100 200

call_user_func_array 與 call_user_func一樣,呼叫使用者自定義方法,第一個引數為要呼叫的方法名,第二個引數是一個數組,陣列內每一個元素是傳遞給呼叫方法的引數。這樣比call_user_func更清晰。

function foo($a,$b){
 echo $a.' '.$b;
}
call_user_func_array('foo',array(100,200)); // 輸出:100 200

呼叫類方法

class Foo{
 function show($a,$b){
  echo $a.' '.$b;
 }
}
call_user_func(array('Foo','show'),200); // 輸出 100 200
call_user_func_array(array('Foo',array(300,400)); // 輸出 300 400

4.func_num_args 與 func_get_arg 與 func_get_args

func_num_args() 返回呼叫方法的傳入引數個數,型別是整型
func_get_arg() 返回指定的引數值
func_get_args() 返回所有引數值,型別是陣列

function foo(){
 $num = func_num_args();
 echo $num; // 2
 for($i=0; $i<$num; $i++){
  echo func_get_arg($i); // 1 2
 }
 print_r(func_get_args()); // Array
} 
foo(1,2);

5.使用php解釋js檔案 在apache httpd.conf中加入:

AddType application/x-httpd-php .js

6.使用冒號表示語句塊

流程控制的書寫模式有兩種語法結構。一種用大括號表示語句塊,一種用冒號表示語句塊。前者一般用於純程式碼中,後者一般用於程式碼和HTML結合時。

大括號表示語句塊

if ($value) {
 // 操作; 
} elseif($value) {
 // 操作; 
} else {
 // 操作;
}

冒號表示語句塊

使用冒號“:”來代替左邊的大括號“{”;使用endif; endwhile; endfor; endforeach; 和endswitch; 來代替右邊的大括號“}”。

if ($value) :
 // 操作
elseif ($value) :
 // 操作
else :
 // 操作
endif

7.php 求餘出現負數處理方法

php int 的範圍是 -2147483648 ~ 2147483647,可用常量 PHP_INT_MAX 檢視。

當求餘的數超過這個範圍,就會出現溢位。從而出現負數。

<?php
echo 3701256461%62; // -13
?>

即使使用floatval 方法把數值轉型為浮點數,但php的求餘運算預設使用整形來計算,因此一樣有可能出現負數。

解決方法是使用浮點數的求餘方法 fmod。

<?php
$res = floatval(3701256461);
echo fmod($res,62); // 53
?>

8.使用file_get_contents post 資料

<?php 
$api = 'http://demo.fdipzone.com/server.php'; 
$postdata = array(
 'name' => 'fdipzone','gender' => 'male'
);
$opts = array(
 'http' => array(
  'method' => 'POST','header' => 'content-type:application/x-www-form-urlencoded','content' => http_build_query($postdata)
 )
);
$context = stream_context_create($opts);
$result = file_get_contents($api,false,$context);
echo $result;
?>

9.設定時區

ini_set('date.timezone','Asia/Shanghai');

到此這篇關於php語法技巧程式碼例項的文章就介紹到這了,更多相關php語法技巧內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!