1.全局變量
創(chuàng)新互聯(lián)建站作為成都網(wǎng)站建設(shè)公司,專注網(wǎng)站建設(shè)公司、網(wǎng)站設(shè)計(jì),有關(guān)企業(yè)網(wǎng)站制作方案、改版、費(fèi)用等問題,行業(yè)涉及成都柔性防護(hù)網(wǎng)等多個(gè)領(lǐng)域,已為上千家企業(yè)服務(wù),得到了客戶的尊重與認(rèn)可。
classMyClass{
static$myStaticVariable=0;
functionmyMethod(){
print self::$myStaticVariable;
}
}
$obj=newMyClass();
$obj->myMethod();
?>
2.全局變量改變
classMyClass{
static$myStaticVariable=0;
public$uniqueId;
function__construct(){
self::$myStaticVariable++;
$this->uniqueId=self::$myStaticVariable;
}
}
$obj1=newMyClass();
print$obj1->uniqueId." ";
$obj2=newMyClass();
print$obj2->uniqueId;
?>
3.靜態(tài)方法
classMyClass{
static functionprintHelloWorld(){
print"hello world ";
self::printMe();
}
static functionprintMe(){
print" zhuchengdie";
}
}
MyClass::printHelloWorld();
?>
4.繼承
classMyClass{
static functionprintHelloWorld(){
print"hello world ";
self::printMe();
}
static functionprintMe(){
print" tony";
}
}
classChild extendsMyClass{
function__construct(){
parent::printHelloWorld();
}
}
$child=newChild();
?>
5.枚舉
classMyClass{
constRED="Red";
constGREEN="Green";
constBLUE="Blue";
functionprintBlue(){
print self::BLUE;
}
}
printMyClass::GREEN;
$obj=newMyClass();
$obj->printBlue();
?>
6.對(duì)象的引用
classMyClass{
public$var=1;
}
$obj1=newMyClass();
$obj2=$obj1;
$obj2->var=2;
print$obj1->var;
?>
打印2
7.克隆
classMyClass{
public$var=1;
}
$obj1=newMyClass();
$obj2=clone$obj1;
$obj2->var=2;
print$obj1->var;
?>
打印1
8.多態(tài)
classCat{
functionmiao(){
print"miao";
}
}
classDog{
functionwangwang(){
print"wangwang";
}
}
functionprintRightSound($obj){
if($obj instanceofCat){
$obj->miao();
}else if($obj instanceofDog){
$obj->wangwang();
}else{
print"Error comes";
}
print"
";
}
printRightSound(newCat());
printRightSound(newDog());
?>
9.多態(tài)與繼承
class
Animal{
functionmakeSound(){
print"I' m other's father";
}
}
class
Cat extendsAnimal{
functionmakeSound(){
print"miao";
}
}
class
Dog extendsAnimal{
functionmakeSound(){
print"wangwang";
}
}
function
printRightSound($obj){
if($obj instanceofAnimal){
$obj->makeSound();
}else{
print"Error comes";
}
print"
";
}
printRightSound(newCat());
printRightSound(newDog());
?>
10.parent::和self::
class
.Ancestor{
constNAME="Ancestor";
function__construct(){
print"In ".self::NAME." constructor
";
}
}
class
Child extendsAncestor{
constNAME="Child";
function__construct(){
parent::__construct();
print"In ".self::NAME." constructor";
}
}
$obj=newChild();
?>
11.抽象
abstract class
MyClass{
abstract functiondraw();
}
class
Square extendsMyClass{
functiondraw(){
}
}
class
Circle extendsMyClass{
functiondraw(){
}
}
?>
12.接口
interface
MyClass{
functiondraw();
}
class
Square implementsMyClass{
functiondraw(){
}
}
class
Circle implementsMyClass{
functiondraw(){
}
}
但是接口是允許多重繼承的:
interface
No1 extendsNo2,No3,…{}
與類實(shí)現(xiàn)接口類似,一個(gè)接口只能繼承與自己互相不沖突的接口(也就是說,如果No2定義了No1已經(jīng)定義的方法或者常量,我們將會(huì)收到報(bào)錯(cuò)信息)。
?>
13.toString()方法
class
MyClass{
function__construct($name){
$this->name=$name;
}
private$name;
function__toString(){
return$this->name;
}
}
$obj=newMyClass("tony");
$obj;
?>
14.異常處理
class
NullHandleException extendsException{
function__construct($message){
parent::__construct($message);
}
}
function
printObject($obj){
if($obj==null){
throw newNullHandleException("printObject received Null object");
}
Print$obj."
";
}
class
MyName{
private$name;
function__construct($name){
$this->name=$name;
}
function__toString(){
return$this->name;
}
}
try
{
printObject(newMyName("bill"));
printObject(null);
printObject(newMyName("Jane"));
} catch(NullHandleException $e) {
print$e->getMessage();
print" in file ".$e->getFile()."
";
print" on line ".$e->getLine()."
";
}
?>
15.在一個(gè)PHP文件里引入另一個(gè)PHP文件
MyClass.php
class MyClass{
function printHelloWorld(){
print “Hello world!”;
}
}
?>
general.php
function _autoload($class_name){
require_once($_SERVER[“DOCUMENT_ROOT”].”/classes/$class_name.php”)
}
?>
main.php
require_once “general.php”;
$obj = new MyClass();
$obj->printHelloWorld();
?>
16.在函數(shù)參數(shù)中提示類的類別
class
ABC{
}
class
EFG{
}
function
onlyWantObject1($obj){
if(!($obj instanceofABC)){
die("only Objects of type ABC can be sent to this function");
}
}
function
onlyWantObject2(ABC $obj){
}
onlyWantObject1(newEFG());
onlyWantObject2(newEFG());
?>
17.get,set方法
class
SetGetClass{
private$arr=array('x'=>null,'y'=>null);
function__get($property){
if(array_key_exists($property, $this->arr)){
return$this->arr[$property];
}else{
print"not exist!";
}
}
function__set($property,$value){
if(array_key_exists($property, $this->arr)){
$this->arr[$property]=$value;
}
}
}
$obj=newSetGetClass();
$obj->__set("x", "xxx");
$obj->__get("x");
?>
18.
call()具有很多用途。下面的例子顯示如何創(chuàng)建一個(gè)授權(quán)模型,通過該模型一個(gè)HelloWorldDelegator類的實(shí)例可以授權(quán)所有的方法去調(diào)用一個(gè)HelloWorld類的實(shí)例call_user_func_array()函數(shù)允許_call()把它的參數(shù)通過call_user_func_array()調(diào)用傳遞給world::display(),后者打印3次“Hello world\n”。然后_call()返回$count的值并在屏幕中打印出來。我們不但可以通過_call()方法調(diào)用到一個(gè)不同的對(duì)象(或者用我們想要的方法處理它),而且我們還可以從_call()函數(shù)返回值,就像正常的方法一樣。
class
HelloWorld{
functiondisplay($count){
for($i=0;$i<$count;$i++){
print"Hello World
";
}
return$count;
}
}
class
HelloWorldDelegator{
private$obj;
function__construct(){
$this->obj=newHelloWorld();
}
function__call($method,$args){
returncall_user_func_array(array($this->obj,$method), $args);
}
}
$obj=newHelloWorldDelegator();
$obj->display(3);
?>
19.迭代
class
HelloWorld{
public$name="John";
public$sex="male";
}
$obj=newHelloWorld();
foreach
($obj as$key=>$value){
print"obj[$key]=$value
";
}
?>
結(jié)果:
obj[name]=John
obj[sex]=male
20.迭代 通過實(shí)現(xiàn)Iterator
PHP5可以讓我們用foreach()循環(huán)在我們的代碼中重載迭代行為,使得它按照我們的類的設(shè)計(jì)執(zhí)行有實(shí)際意義的遍歷。
注意:PHP5不僅可以讓我們重載這種行為,而且它還可以讓編寫擴(kuò)展的作者重寫類似的行為,這已經(jīng)讓迭代器支持多種PHP擴(kuò)展,例如SimpleXML和SQite。
為了在我們的類中重載迭代器,我們需要執(zhí)行一些PHP預(yù)先定義 的接口。接口如下:
interface Tracersable
interface IteratorAggregate interface Iterator
Iterator getIterator() void rewind()
void next()
bool valid()
mixed key()
mixed current()
任何實(shí)現(xiàn)Tracersable接口的類都可以用foreach結(jié)構(gòu)遍歷。但是Tracersable是一個(gè)空的接口而且不能直接被執(zhí)行;反之,我們可以執(zhí)行Iterator或者IteratorAggregate,他們都是從Tracersable繼承來的。
主要的接口是Iterator。它定義了我們需要執(zhí)行的方法以便給我們的類提供foreach迭代的功能。這些方法應(yīng)該是公共的,如下表:
interface Interator | |
void rewind() | 重新把迭代器指向列表開始處 |
mixed current() | 返回當(dāng)前位置的值 |
mixed key() | 返回當(dāng)前位置的關(guān)鍵字 |
void next() | 把迭代器移動(dòng)到下一個(gè)關(guān)鍵字/值對(duì) |
bool valid() | 返回true/false值,判斷是否有更多的值 |
例子:
class
NumberSquared implementsIterator{
private$start,$end;
private$cur;
public function__construct($start,$end){
$this->start=$start;
$this->end=$end;
}
public functionrewind(){
$this->cur=$this->start;
}
public functionkey(){
return$this->cur;
}
public functioncurrent(){
returnpow($this->cur, 2);
}
public functionnext(){
$this->cur++;
}
public functionvalid(){
return$this->cur<=$this->end;
}
}
$obj=newNumberSquared(3, 7);
foreach
($obj as$key=>$value){
print"The square of$key is$value
";
}
?>
結(jié)果:
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
21.這個(gè)代碼的輸出和先前的例子輸出是一樣的。我們可以清楚的看到IteratorAggregate接口可以讓我們把我們的類的主要功能與迭代遍歷它所需要的方法分離到兩個(gè)獨(dú)立的實(shí)體中
class
NumberSquared implementsIteratorAggregate{
private$start,$end;
public function__construct($start,$end){
$this->start=$start;
$this->end=$end;
}
public functiongetIterator(){
return newNumberSquaredIterator($this);
}
public functiongetStart(){
return$this->start;
}
public functiongetEnd(){
return$this->end;
}
}
class
NumberSquaredIterator implementsIterator{
private$obj;
private$cur;
public function__construct($obj){
$this->obj=$obj;
}
public functionrewind(){
$this->cur=$this->obj->getStart();
}
public functionkey(){
return$this->cur;
}
public functioncurrent(){
returnpow($this->cur, 2);
}
public functionnext(){
$this->cur++;
}
public functionvalid(){
return$this->cur<=$this->obj->getEnd();
}
}
$obj=newNumberSquared(3, 7);
foreach
($obj as$key=>$value){
print"The square of$key is$value
";
}
?>
22.單例模式
在這個(gè)例子中,構(gòu)造函數(shù)和克隆方法都被定義為private。這么做的原因是為了防止開發(fā)者用new或者clone運(yùn)算符錯(cuò)誤的創(chuàng)建第二個(gè)Logger類的實(shí)例;因此,getInstance()是唯一可以訪問單件類實(shí)例的方法。
class
Logger{
private function__construct(){}
private function__clone(){}
static private$instance=null;
functionLog($str){}
static functiongetInstance(){
if(self::$instance==null){
self::$instance=newLogger();
}
return self::$instance;
}
}
Logger::getInstance()->Log("check");
?>
23.工廠模式
abstract class
User{
protected$name=null;
function__construct($name){
$this->name=$name;
}
functiongetName(){
return$this->name;
}
functionhasReadPermission(){
return true;
}
functionhasModifyPermission(){
return false;
}
functionhasDeletePermission(){
return false;
}
functionwantsFlashInterface(){
return true;
}
}
class
GuestUvser extendsUser{
}
class
CustomerUser extendsUser{
functionhasModifyPermission(){
return true;
}
}
class
AdminUser extendsUser{
functionhasModifyPermission(){
return true;
}
functionhasDeletePermission(){
return true;
}
functionwantsFlashInterface(){
return false;
}
}
class
UserFactory{
private static$user=array("Andi"=>"admin","stig"=>"guest","Derick"=>"custormer");
static functionCreate($name){
if(!isset(self::$user[$name])){
print"用戶不存在";
return;
}
switch(self::$user[$name]){
case"guest":
return newGuestUvser($name);
break;
case"customer":
return newCustomerUser($name);
break;
case"admin":
return newAdminUser($name);
break;
}
}
}
function
boolToStr($b){
if($b==true){
return"Yes
";
}else{
return"No
";
}
}
function
displayPermissions(User $obj){
print$obj->getName()."'s permissions:
";
print"Read:".boolToStr($obj->hasReadPermission());
print"
";
print"Modify:".boolToStr($obj->hasModifyPermission());
print"
";
print"Delete:".boolToStr($obj->hasDeletePermission());
}
function
displayRequirements(User $obj){
if($obj->wantsFlashInterface()){
print$obj->getName()." requires Flash
";
}
}
$logins=array("Andi","stig","Derick");
foreach
($logins as$log){
displayPermissions(UserFactory::Create($log));
displayRequirements(UserFactory::Create($log));
}
?>
24.讀文件
$filename=fopen("test.php", "r");
do
{
$mychar=fgets($filename,1024);
echo
$mychar;
}while(!feof($filename));
fclose($filename);
?>
25.寫文件
$filename="ddd.txt";
$wr1="我先被寫入的";
$wr2="我后被寫入的哦";
if
(is_writable($filename)){
if(!$hand=fopen($filename, "w")){
print"不能打開文件";
exit;
}
if(!fwrite($hand , $wr1)){
print"不能寫入文件";
exit;
}
print"寫入成功";
fclose($hand);
$hand=fopen($filename, "w");
fwrite($hand, $wr2);
fclose($hand);
print"第二次成功!";
}
?>
后面寫的內(nèi)容會(huì)覆蓋前面的
26.寫文件(以寫入方式打開)會(huì)追加添加
$filename="ddd.txt";
$wr1="我先\t被寫入的\r\n";
$wr2="我后被寫入的哦";
if
(is_writable($filename)){
if(!$hand=fopen($filename, "a")){
print"不能打開文件";
exit;
}
if(!fwrite($hand , $wr1)){
print"不能寫入文件";
exit;
}
print"寫入成功";
fclose($hand);
$hand=fopen($filename, "a");
fwrite($hand, $wr2);
fclose($hand);
print"第二次成功!";
}
?>
27.指針
$filename="ddd.txt";
$handle=fopen($filename, "r");
//讀取第一行
$buffer=fgets($handle,1024);
echo
$buffer."
";
//讀取第二行
$buffer=fgets($handle,1024);
echo
$buffer."
";
//讀取第三行
$buffer=fgets($handle,1024);
echo
$buffer."
";
//將指針回到文件開始,繼續(xù)讀取第一行數(shù)據(jù)
rewind($handle);
$buffer=fgets($handle,1024);
echo
$buffer."
";
fclose($handle);
?>
28.讀取文件里的文件名及目錄名
$dir="D:/Email";
if
(is_dir($dir)){
$dp=opendir($dir);
print_r("目錄已被打開
");
while($filen=readdir($dp)){
print_r($filen."
");
}
closedir($dp);
}else{
echo"目錄不存在";
}
?>
29.循環(huán)讀取目錄
<
table border="1">
function
direct($dir){
$dp=opendir($dir);
while($filen=readdir($dp)){
if($filen!='.'&& $filen!='..'){
$path=$dir."/".$filen;
if(is_dir($path)){
echo"目錄:".$path;
echo"
";
direct($path);
}else{
echo"
echo"
echo"
}
}
}
}
$dir="D:/TestFolder";
direct(realpath($dir));
?>
30.創(chuàng)建目錄
$dirname="pic";
$str=mkdir($dirname,100);
if
($str){
echo"創(chuàng)建成功";
}
?>
31.格式化當(dāng)前時(shí)間
echo
date('Y m d H:i:s',time());32.正則表達(dá)式
$result=preg_match("/love/", "Oh my love");//判斷字符串是否包含love
$result=ereg("^Oh", "Oh my love");//判斷字符串首位是不是Oh
$result=ereg("ve$", "Oh my love");//判斷字符串最后是否是ve