您的位置:首页 > 编程语言 > PHP开发

php语法技巧代码实例

2021-02-01 04:06 621 查看

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'), 100, 200); // 输出 100 200
call_user_func_array(array('Foo','show'), 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语法技巧内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php 语法 技巧