目录
12.10更新,复盘的时候发现了些许错别字,已改正。如有错误,请读者指出,共同进步。
基本语法
输出语句
print statement;
echo
echo statement;
区别
- print只能输出一个字符串,并且始终返回1
- echo能够输出一个及以上的字符串,并且不返回任何值,且echo比print稍快些
print搭配br\p\pre分行显示
php中的换行处理的三种方法
- <p>content</p>
- content<br>
- <pre>content</pre>
数据类型
八种数据类型
四种基本类型:int整型、float\double浮点型、boolean\bool布尔型、string字符串
两种复合类型:array数组、object对象
两种特殊类型:resource资源、NULL空
对象数据类型
<?php
class foo{
function do_foo(){
echo "hello";
}
}
$bar = new foo;
$bar->do_foo();
?>
resource资源数据类型
对文件进行操作
<?php
if(!file_exists("test.txt"){
$fh = fopen("test.txt","w");//打开文件
get_resource_type($fh);//输出stream
fclose($fh);//关闭文件
}
?>
NULL数据类型
三种情况认定为空:
- 被赋值为NULL
- 没有被赋值
- 被unset()
空类型一定全是大写,不能写为null
判断数据类型的方法
- gettype() 返回数据类型
- is_type() 返回true和false
- var_dump()返回数据类型和值
算术运算
函数 | 功能 |
abs(n) | 绝对值 |
ceil(a),floor(n) | 向上取整、向下取整 |
cos(a),sin(a),tan(a) | 三角函数 |
lod(n),log10(n) | 对数、自然对数 |
min(a,b,...),max(a,b,...) | 最大值、最小值 |
pow(base,exp) | 乘方 |
rand(),rand(min,max) | 产生随机整数 |
round(n),round(n,digits) | 四舍五入 |
sqrt(n) | 平方根 |
常量 | 描述 |
M_PI | π |
M_E | e,2.7182818... |
M_LN2 | loge2,0.693147 |
变量
- PHP变量总是以$开头
- 在PHP在,所有变量都对大小写敏感,区分大小写
- 变量总是通过赋值隐性声明,不用专门支出其数据类型
- PHP是一种松散类型语言类似于JavaScript和Python
- 如果一个变量没有被赋值,则该变量的初值可能是0、0.0、空字符串、空数组
运算符 | 描述 |
= | 赋值 |
+= | 加后赋值 |
-= | 减后赋值 |
*= | 乘后赋值 |
/= | 除后赋值 |
%= | 求余后赋值 |
++ | 递增 |
-- | 递减 |
字符串
字符串运算符
串接
<?php
$txt1="hello";
$txt2=$txt1." world!";//txt2="hello world!";
?>
串接赋值
<?php
$txt1="hello";
$txt1.=" world!";//txt1="hello world!";
?>
字符串函数
函数 | 功能 |
strlen(s) | 返回字符串的长度 |
strtoupper(s) strtolower(s) | 将字符串转换成大写 将字符串转换成小写 |
trim(s) ltrim(s) rtrim(s) | 从两端删除字符串中的空白字符 从左端删除字符串中的空白字符 从右端删除字符串中的空白字符 |
strstr(haystack,needle) strrchr(h,n) | 查找字符串在另一个字符串中首次出现的位置 查找字符串在另一个字符串中最后一次出现的位置 |
substr(s,start) substr(s,start,length) | 返回字符串的一部分 |
str_replace(s,from,to) | 替换字符串中的一些字符 |
explode(delim,s) implode(delim,s) str_split(s) | 将字符串打散成数组 将数组元素组合成为一个字符串 把字符串分割到数组中 |
strcmp(s1,s2) strcasecmp(s1,s2) | 比较两个字符串(对大小写敏感) 比较两个字符串(对大小写不敏感) |
str_shuffle(s) | 随机的打乱字符串中的所有字符 |
strrev(s) | 反转字符串 |
htmlspecialchars(s) | 将一些预定义的字符转换成HTML实体 |
ord(c) chr(n) | 返回字符串中第一个字符的ASCII值 从指定的ASCII值返回字符 |
str_pad(s,length) | 把字符串填充为新的长度 |
str_repeat(s,times) | 将字符串重复指定的次数 |
printf(format,...) | 输出格式化的字符串 |
sprintf(format,...) sscanf(s,format,...) | 把格式化的字符串写入一个变量中 根据指定的格式解析来自一个字符串的输入 |
similar_text(s1,s2) | 计算两个字符串的匹配字符的数目 |
levenshtein(s1,s2) | 返回两个字符串之间的levenshtein距离 |
对字符串中的变量解释
php可以对字符串中出现的变量进行解释,并将变量的值插入到字符串中,但是对字符串的解释只对双引号" "有效,对单引号' '无效。PHP对单引号中的变量不做解释,会直接当字符串进行处理。所以为了不必要的麻烦,我们有时候可以用{ }来封闭变量。
举个例子:
<?php
$age=20;
echo "You are".$age."years old.<br \>";
echo "You are $age years old.<br \>";
// You are 20 years old.
echo 'You are $age years old .<br \>';
// You are $age years old.
echo "Today is your $ageth birthday. <br\>";
// $ageth not found
echo "Today is your {$age}th birthday. <br\>";
// Today is your 20th birthday.
布尔逻辑
PHP中的任何值都可以作为布尔值
一般0和NULL都为false,其他值都是true
可以作为false的值有如下几种情况:
- 0,0.0
- "","0",NULL
- 没有元素的数组array()
- 没有被赋值的变量
控制语句
if/else
<?php
if ($a==5) {
print "a等于5";
} else if ($a==6) {
print "a等于6";
} else {
print "a既不等于5又不等于6";
}
?>
for loop
<?php
for($i=0;$i<10;$i++){
print "$i squared is".$i*$i.".\n";
}
?>
foreach loop
我们通常使用foreach来遍历数组。
<?php
$stooges = array("Larry", "Moe", "Curly", "Shemp");
foreach ($stooges as $stooge) {
print "Moe slaps $stooge\n";
}
?>
for loop和foreach loop的相互转换
<?php
$stooges = array("Larry", "Moe", "Curly", "Shemp");
foreach ($stooges as $stooge) {
print "Moe slaps $stooge\n";
}
for ($i = 0; $i < count($stooges); $i++) {
print "Moe slaps {$stooges[$i]}\n";
}
?>
while loop
<?php
$x = 1;
while ($x <= 5) {
echo "这个数字是:$X";
$x++;
}
?>
do..while loop
<?php
$x=1;
do{
echo "这个数字是:$x";
$x++;
}while($x<=5);
?>
函数
- 函数是可以在程序中重复使用的语句块。
- 函数在页面加载时不会立即执行,只有在函数被调用时才会被执行。
- 用户自定义的函数声明应以function开头,PHP中函数名不区分大小写。
- 函数名可以以字母或下划线开头,不能以数字开头。
- 函数的参数类型和返回值类型可以不写。
- 没有返回语句的函数被含蓄定义为空类型。
- 函数可以在PHP代码中的任何位置声明。
自定义函数举例(求两点举例):
<?php
function slope($x1, $y1, $x2, $y2)
{
$result = ($y2 - $y1) / ($x2 - $x1);
return $result;
}
$x = 4;
$y = 6;
$my_slope = slope(0, 0, $x, $y);
带缺省参数值的函数举例:
<?php
function print_separated($str, $separator = ",")
{
if (strlen($str) > 0) {
print $str[0];
for ($i = 1; $i < strlen($str); $i++) {
print $separator . $str[$i];
}
}
}
print_separated("hello");
print_separated("hello", ".");
?>
值传递
举例:
<?php
function make_bigger($num)
{
$num = $num * 2;
}
$x = 5;
make_bigger($x);
print $x; //5
?>
值传递就是将变量$x的值复制到函数中相应的变量$num中,但是变量$x的值并不会发生变化。
参数传递
举例:
<?php
function make_bigger(&$num)
{
$num = $num * 2;
}
$x = 5;
make_bigger($x);
print $x; //10
?>
参数传递在变量$num中存放变量$x的地址,即将变量$x的地址复制到函数中,主调函数中变量$x的值会发生变化。
变量作用域
函数之外声明的变量属于全局变量global,在整个程序中都可以使用。
在函数中定义的变量属于局部变量local,仅在定义它的函数中使用。
PHP中没有比函数更小级别的变量作用域范围了。
文件包含语句
语句 | 描述 |
include(f) | 将文件的内容导入到另一个文件中 |
require(f) | 功能同include,但是如果被导入的文件不存在,会显示错误 |
include_once(f) require_once(f) | 功能同include和require,但是不允许相同的文件在同一个页面被导入多次 |
数组
- PHP中数组索引是从0开始的。
- 同一个PHP数组中可以存储不同类型的值。
- PHP数组可以动态的增加或减少。
PHP中有三种类型的数组:
- 索引数组
- 多维数组
- 关联数组
数组函数
array_diff() | 比较数组,返回差集(只比较键值) |
array_fill() | 用给定的键值填充数组 |
array_filter() | 用回调函数过滤数组中的元素 |
array_flip() | 交换数组中的键和值 |
array_intersect() | 比较数组,返回交集(只比较键值) |
array_key_exists() | 检查指定的键名是否存在在数组中 |
array_map() | 把数组中的每个值发送到用户自定义的函数中,并返回新的值 |
array_merge() | 把一个或多个数组合并为一个数组 |
array_pop() | 删除数组的最后一个元素(出栈) |
array_product() | 计算数组中所有值的乘积 |
array_push() | 将一个或者多个元素插入到数组的末尾(入栈) |
array_rand() | 返回数组中的一个或者多个随机的键 |
array_reduce() | 通过使用用户自定义的函数,以字符串返回数组 |
array_reserve() | 以相反的顺序返回数组 |
array_search() | 搜索数组中给定的值并返回键名 |
array_shift() | 删除数组中的首个元素,并返回被删除元素的值 |
array_slice() | 返回数组被选定的部分 |
array_splice() | 删除并替换数组中指定的部分 |
array_sum() | 返回数组中所有值的和 |
array_unique() | 删除数组中的重复值 |
array_unshift() | 在数组的开头插入一个或者多个元素 |
array_values() | 返回数值中所以的值 |
arsort() | 对关联数组按照键值进行降序排序 |
asort() | 对关联数组按照键值进行升序排序 |
count() | 返回数组中元素的个数 |
ksort() | 对数组按照键名进行排序 |
list() | 把数组的值赋给一些变量 |
range() | 创建包含指定范围单元的数组 |
rsort() | 对数组逆向排序 |
shuffle() | 将数组打乱 |
sort() | 对数组排序 |
usort() | 使用用户自定义的比较函数对数组进行排序 |
从数组中删除元素举例:
<pre>
<?php
$grades = array(50, 60, 70, 80, 90, 100);
array_splice($grades, 2, 3);
print "\ngrades array contains " . count($grades) . "elements(array_splice).\n";
print_r($grades);
unset($grades[1]);
print "grades array contains " . count($grades) . "elements(unset).\n";
print_r($grades);
?>
</pre>
数组中的for循环和foreach循环求最大值:
<?php
function array_max_foreach($a)
{
$largest = $a[0];
for ($i = 0; $i < count($a); $i++) {
$largest = max($largest, $a[$i]);
}
return $largest;
}
function array_max_for($a)
{
$largest = $a[0];
foreach ($a as $num) {
$largest = max($largest, $num);
}
return $largest;
}
?>
字符串和数组相互转换的函数
explode 将字符串转换成数组
implode 将数组转换成字符串
<?php
$s = "UW CSE 190 M";
$a = explode(" ", $s);
$s2 = implode("---", $a);
?>
文件操作
函数 | 功能 |
chmod(f,mode) chgrp(f,group) chown(f,owner) | 更改文件的权限,组别和所有者 |
copy(src,dst) | 复制文件 |
disk_free_space(dir) | 返回目录的可用空间 |
file(f) file(f,flags) | 把整个文件读入一个数组中 |
file_exists(f) | 检查文件或者目录是否存在 |
file_get_contents(f) | 将文件读入字符串 |
file_put_contents(f,text) file_put_contents(f,text,flag) | 将字符串写入文件 |
glob(pattern) | 返回一个包含匹配指定模式的文件名/目录的数组 |
filetime(f) | 返回文件上次的修改时间 |
fileperms(f) | 返回文件的权限 |
filesize(f) | 返回文件的大小 |
is_dir(f) | 判断指定的文件名是否是一个目录 |
is_readable(f) is_writeable(f) | 判断文件是否可读/可写 |
mkdir(dir) mkdir(dir,perms,recursive) | 创建目录 |
rename(scr,dsr) | 重命名文件或目录 |
rmdir(dir) | 删除空目录 |
scandir(dir) | 返回目录在所有的文件名 |
unlink(f) | 删除文件 |
类和对象
class name{
private $name;
public function _construct(name) {
statement;
}
public function name(parameters) {
statements;
}
}
$this -> fieldName;
$this -> methodName(parameters);
举例:银行账户类
<?php
class BankAccount
{
private $name;
private $balance;
public function __construct($name)
{
$this->name = $name;
$this->balance = 0.00;
}
public function getBalance()
{
return $this->balance;
}
public function getName()
{
return $this->name;
}
public function deposit($amount)
{
if ($amount >= 0.00) {
$this->balance += $amount;
}
}
public function withdraw($amount)
{
if ($amount >= 0.00 && $amount <= $this->balance) {
$this->balance -= $amount;
}
}
public function __toString()
{
return "{" . $this->name . ",$" . $this->balance . "}";
}
}
$account1 = new BankAccount("张三");
$account1->deposit(5.00);
$account1->withdraw(1.25);
$account1->withdraw(1000.00);
$account2 = new BankAccount("李四");
$account2->deposit(999.00);
$account2->deposit(-15.00);
?>
<div>
<strong>Account1:</strong><?= $account1 ?><br />
<strong>Account2:</strong><?= $account2 ?>
</div>
参考资料
中国大学mooc-西安交通大学-《Web编程技术》第七章PHP
菜鸟教程
w3school