php语法基础(一)- 变量、常变量、函数、分支和循环、字符串、数组、类、时间、日期、包含文件、文件及图片读写等

来源:转载

测试环境

phpstorm9
xampp5.6.14
linux-xx

变量、常变量、函数、分支和循环

<?php
//当只是php代码的时候,<?php末尾标识符省略,若包含html代码,则需将php末尾标识符加上
//变量
$a = 10;
$b = 15.000000000001;//精确到E-12
echo $a + $b ."
";//常量
const CONST_VALUE1 = 11; //php5
define("CONST_VALUE2", 12); //php4
echo CONST_VALUE1 ."
";
echo CONST_VALUE2 ."
";//函数(一)
function sayHello() {
echo "hello!"."
";
}
//调用函数
sayHello();//函数(二) //回调 //函数可作为参数进行传递
$func = "sayHello";
$func();
$aaa = function() {
echo "hello 呵呵呵!";
};
$aaa();//函数(三) //含参函数
function sayName($name) {
echo "hello ". $name . "!
";
}
sayName("张三");
sayName("李四");
//函数(四) //多个参数
function add($a, $b) {
echo "a=$a, b=$b
"; //a=1, b=2
echo "a+b=($a+$b)
"; //a+b=(1+2)
echo "a+b=".($a+$b)."
"; //a+b=3
}
add(1,2);
//函数(五) //返回值
function getNum($num) {
return $num;
}
echo getNum(2)."
"; //2//分支 if switch
function getLevelByIf($score) {
if ($score>100 || $score<0) {
return "illegal!";
} else if ($score>90) {
return "excellent";
} else if ($score>80) {
return "good";
} else {
return "bad";
}
}
echo getLevelByIf(101)."
";
function getLevelBySwitch($score) {
switch((intval($score/10))) { //intval是php整数函数
case 10:
case 9:
return "excellent"; //
case 8:
return "good";
case 7:
case 6:
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
return "bad";
default:
return "illegal!";
}
}
echo getLevelBySwitch(91)."
";//循环 for while
function getSumByFor($start, $end) {
$sum = 0;
for($i=$start; $i<=$end; $i++) {
$sum += $i; //可以 break或continue
}
return $sum;
}
echo getSumByFor(1,100) . "
";
function getSumByWhile($start, $end) {
$sum = 0;
$i = $start;
while ($i<=$end) {
$sum += $i;
$i++;
}
return $sum;
}
echo getSumByWhile(1,100) . "
";
function getSumByDoWhile($start, $end) {
$sum = 0;
$i = $start;
do {
$sum += $i;
$i++;
} while ($i<=$end);
return $sum;
}
echo getSumByDoWhile(1,100) . "
";
?>

字符串和数组(String&Array)

<?php
/*字符串的使用*/
//位置
$str = 'Hello PHP!';
echo strpos($str,'PH').'
'; //6
//子串
echo substr($str, 2, 3).'
'; //llo 从2位置,长度为3
echo substr($str, 2).'
'; //llo PHP! 从2位置,到结尾
//等分割
$result = str_split($str);
print_r($result); //打印数组 Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => P [7] => H [8] => P [9] => ! )
echo '
';
$result = str_split($str, 3);
print_r($result); //Array ( [0] => Hel [1] => lo [2] => PHP [3] => ! )
echo '
';
//不等分割
$result = explode(' ', $str);
print_r($result); //Array ( [0] => Hello [1] => PHP! )
echo '
';
//连接
$str = '窗前明月光'.'
'.'疑是地上霜'.'
';
echo $str.'
';
$str = "$str 举头望明月
低头思故乡
";
echo $str;
?>

<?php
//基本
$array = array(); //array可以存放所有类型的数据
$array[0] = "hello";
$array[1] = "world";
$array[2] = 2;
$array[3] = 3.14;
print_r($array); //Array ( [0] => hello [1] => world [2] => 2 [3] => 3.14 )
echo "
";
//初始化
$array = array('a'=>'hehe', 'b'=>'haha');
print_r($array); //Array ( [a] => hehe [b] => haha )
echo "
";
//push
for($i=0; $i<5; $i++) {
array_push($array, "item_$i");
}
print_r($array); //Array ( [a] => hehe [b] => haha [0] => item_0 [1] => item_1 [2] => item_2 [3] => item_3 [4] => item_4 )
echo "
";
//以key-value形式存放数据
$array['a'] = "aaaa";
$array['a'] = "aaaaaaaaa";
$array['b'] = "bbbb";
echo $array['a']."
"; //aaaaaaaaa
echo $array['b']."
"; //bbbb
echo "
";
//遍历
foreach($array as $key=>$value) {
echo "$key=$value
";
}
echo "
";
?>

时间、日期、数组、JSON

<?php
//时间戳
echo time() ."
";
//时区
echo date_default_timezone_get() ."
"; //默认为Europe/Berlin
//日期
date_default_timezone_set("Asia/Shanghai"); //改时区为上海时间 [参考]http://php.net/manual/en/timezones.asia.php
echo date('Y-m-d H:i:s') . "
"; //F2为文档提示键 2015-11-20 15:11:59
//时间戳和日期的互转
$date = date('Y-m-d H:i:s', 1448003519);
echo $date . "
"; //2015-11-20 15:11:59
echo strtotime($date) ."
"; //1448003519//数组转json
$array = array(1,2,5,8,0, "hello", "zhangsan", array("lover"=>"xiaojuan", "lover_age"=>23));
$obj = array("lover"=>"xiaojuan", "lover_age"=>23);
echo json_encode($array) ."
"; //[1,2,5,8,0,"hello","zhangsan",{"lover":"xiaojuan","lover_age":23}]
echo json_encode($obj) ."
"; //{"lover":"xiaojuan","lover_age":23}
//json转数组
$jsonStr = '{"lover":"xiaojuan","lover_age":23}';
$obj = json_decode($jsonStr);
echo $obj->lover ." " .$obj->lover_age ."
";
?>

include&require

<?php
/*
* 在一个php文件中引入另一个php文件有如下四种方式:
* 1.include xxx.php 包含(包含一次,被包含文件的代码执行一次,[注]若文件被包含两次以上,则可能导致被包含文件的函数重复定义)
* 2.include_once xxx.php 包含一次(被包含文件的代码只执行第一次,不会造成函数的重复定义)
* 3.require xxx.php 依赖(与include的区别是错误提示级别不同,即:若被包含或依赖的文件找不到或出错,则require会报错,程序终止,而include则只是警告,程序继续执行)
* 4.require_once xxx.php 依赖一次
*/
include "include-require-lib.php";
sayHello();
include_once "include-require-lib.php"; //
//include-require-lib.php
<?php
echo "----include-require-lib.php----
";
function sayHello() {
echo "hello world!
";
}
/**
* 运行结果:
* ----include-require-lib.php----
* hello world!
*/
?>

类的命名空间、属性、方法(静态xx、成员xx、常量、构造方法…)


//index.php
<?php
require_once "namespace01/Student.php";
require_once "namespace02/Student.php";
$student = new /namespace01/Student();
$student->setName("张三");
$student->setAge(23);
echo $student->__toString();
new /namespace01/Student();
//new /namespace01/Student(); //抛出异常,程序终止!
echo "
";
$student = new /namespace02/Student("小娟", 22);
echo $student->__toString();
echo "
";
?>//namespace01/Student.php
<?php
/**
* Created by PhpStorm.
* User: kignglyjn
* Date: 2015/11/3
* Time: 22:05
*/
namespace namespace01;
class Student {
//成员属性
private $name, $age;
//静态属性
public static $NUM = 0;
//常量
const MAX_STUDENT_NUM = 2;
/*============================构造方法====================================*/
public function __construct() {
if (Student::$NUM >= Student::MAX_STUDENT_NUM) {
throw new /Exception("不能创建2个以上的学生!!!");
}
echo "The constructor of namespace01's Student
";
Student::$NUM++;
}
/*public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}*/ /*=============================静态方法===================================*/
public static function study() {
echo "study...
";
} /*=============================成员方法===================================*/
/**
* @return mixed
*/
public function getName() {
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name) {
$this->name = $name;
}
/**
* @return mixed
*/
public function getAge() {
return $this->age;
}
/**
* @param mixed $age
*/
public function setAge($age) {
$this->age = $age;
}
function __toString() {
return "name=$this->name age=$this->age
";
}
public function sayHello() {
echo "hello namespace01!
";
}
}?>//namespace02/Student.php
<?php
namespace namespace02;
class Student {
//属性
private $name, $age;
/**
* @param $name 姓名
* @param $age 年龄
*/
public function __construct($name, $age)
{
echo "The constructor of namespace02's Student
";
$this->name = $name;
$this->age = $age;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getAge()
{
return $this->age;
}
/**
* @param mixed $age
*/
public function setAge($age)
{
$this->age = $age;
}
function __toString()
{
return "name=$this->name age=$this->age
";
}
public function sayHello()
{
echo "hello namespace02!
";
}
}?>

运行结果:


类的继承与方法重写


//index.php
<?php
require_once "namespace01/Student.php";
$student = new /namespace01/Student("xx小学");
echo $student->__toString();
echo "
";
$student->sayHello();
echo "
";
?>//namespace01/Person.php
<?php
namespace namespace01;
class Person {
private $name, $age, $sex;
/**
* Person constructor.
* @param $name
* @param $age
* @param $sex
*/
public function __construct($name, $age, $sex)
{
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getAge()
{
return $this->age;
}
/**
* @param mixed $age
*/
public function setAge($age)
{
$this->age = $age;
}
/**
* @return mixed
*/
public function getSex()
{
return $this->sex;
}
/**
* @param mixed $sex
*/
public function setSex($sex)
{
$this->sex = $sex;
}
function __toString()
{
return "$this->name $this->age $this->sex";
}
function sayHello() {
echo "hello person!
";
}
}
?>//namespace01/Sudent.php
<?php
namespace namespace01;
require_once "namespace01/Person.php";
class Student extends Person {
private $school;
/**
* Student constructor.
* @param $school
*/
public function __construct($school)
{
parent::__construct("张三", 23, "男");
$this->school = $school;
}
/**
* @return mixed
*/
public function getSchool()
{
return $this->school;
}
/**
* @param mixed $school
*/
public function setSchool($school)
{
$this->school = $school;
}
/*============================方法重写====================================*/
function __toString()
{
return parent::__toString()." ".$this->school; // TODO: Change the autogenerated stub
}
function sayHello()
{
echo "hello student!"; // TODO: Change the autogenerated stub
}
}
?>

运行结果:


文件的读写

<?php
//w
$f = @fopen("data.txt", "w"); //@符号 表示忽略警告
if($f) {
//default codeStyle is current file's //如果出现权限问题,chmod 777 tools //更改tools目录的权限
fwrite($f, "床前明月光!/n疑是地上霜!");
fclose($f);
echo "write ok!
";
} else {
echo "创建文件失败!
";
}
//r
$f = @fopen("data.txt", "r");
while (!feof($f)) {
$content = fgets($f); //read a line
echo $content ."
";
}
fclose($f);
//get content
echo file_get_contents("data.txt"); //床前明月光! 疑是地上霜!
?>

图片及图片文件的操作


画一张图片

<?php
$img = imagecreate(400, 300);
imagecolorallocate($img, 255, 255, 255); //background-color
imageellipse($img, 200, 200, 50, 50, imagecolorallocate($img, 255, 0, 0)); //draw an red ellipse
header("Content-type: image/png"); //set Content-type
imagepng($img);
?>

运行结果:


给图片设置水印

<?php
$img = imagecreatefrompng("005.png");
header("Content-type: image/png");
imagestring($img, 5, 20, 20, "this is a water mark! --kinglyjn", imagecolorallocate($img, 255, 0, 0));
imagepng($img);
?>

运行结果:

分享给朋友:
您可能感兴趣的文章:
随机阅读: