PHP面向對象編程

1.全局變量

<?php

class MyClass{

static $myStaticVariable=0;

function myMethod(){

print self::$myStaticVariable;

}

}

 

$obj=new MyClass();

$obj->myMethod();

?>

2.全局變量改變

<?php

class MyClass{

static $myStaticVariable=0;

public $uniqueId;

function __construct(){

self::$myStaticVariable++;

$this->uniqueId=self::$myStaticVariable;

}

}

 

$obj1=new MyClass();

print $obj1->uniqueId." ";

$obj2=new MyClass();

print $obj2->uniqueId;

?>

 

3.靜態方法

<?php

class MyClass{

static function printHelloWorld(){

print "hello world ";

self::printMe();

}

 

static function printMe(){

print " zhuchengdie";

}

}

MyClass::printHelloWorld();

 

?>

 

4.繼承

<?php

class MyClass{

static function printHelloWorld(){

print "hello world ";

self::printMe();

}

 

static function printMe(){

print " tony";

}

}

class Child extends MyClass{

function __construct(){

parent::printHelloWorld();

}

}

 

$child=new Child();

 

?>

 

5.枚舉

<?php

class MyClass{

const RED="Red";

const GREEN="Green";

const BLUE="Blue";

function printBlue(){

print self::BLUE;

}

}

print MyClass::GREEN;

$obj=new MyClass();

$obj->printBlue();

 

?>

6.對象的引用

<?php

class MyClass{

public $var=1;

}

$obj1=new MyClass();

$obj2=$obj1;

$obj2->var=2;

print $obj1->var;

?>

打印2

7.克隆

<?php

class MyClass{

public $var=1;

}

$obj1=new MyClass();

$obj2=clone $obj1;

$obj2->var=2;

print $obj1->var;

?>

打印1

 

8.多態

<?php

class Cat{

function miao(){

print "miao";

}

}

class Dog{

function wangwang(){

print "wangwang";

}

}

 

function printRightSound($obj){

if($obj instanceof Cat){

$obj->miao();

}else if($obj instanceof Dog){

$obj->wangwang();

}else{

print "Error comes";

}

print "<br>";

}

printRightSound(new Cat());

printRightSound(new Dog());

?>

9.多態與繼承

<?php

class

Animal{

function makeSound(){

print "I' m other's father";

}

}

 

class

Cat extends Animal{

function makeSound(){

print "miao";

}

}

class

Dog extends Animal{

function makeSound(){

print "wangwang";

}

}

 

function

printRightSound($obj){

if($obj instanceof Animal){

$obj->makeSound();

}else{

print "Error comes";

}

print "<br>";

}

printRightSound(new Cat());

printRightSound(new Dog());

?>

10.parent::和self::

<?php

class

.Ancestor{

const NAME="Ancestor";

function __construct(){

print "In ".self::NAME." constructor<br>";

}

}

 

class

Child extends Ancestor{

const NAME="Child";

function __construct(){

parent::__construct();

print "In ".self::NAME." constructor";

}

}

$obj=new Child();

?>

11.抽象

<?php

abstract class

MyClass{

abstract function draw();

}

class

Square extends MyClass{

function draw(){

 

}

}

class

Circle extends MyClass{

function draw(){

 

}

}

?>

12.接口

<?php

interface

MyClass{

function draw();

}

class

Square implements MyClass{

function draw(){

 

}

}

class

Circle implements MyClass{

function draw(){

 

}

}

但是接口是允許多重繼承的:

interface

No1 extends No2,No3,…{}

與類實現接口類似,一個接口只能繼承與自己互相不衝突的接口(也就是說,如果No2定義了No1已經定義的方法或者常量,我們將會收到報錯信息)。

?>

13.toString()方法

<?php

class

MyClass{

function __construct($name){

$this->name=$name;

}

private $name;

 

function __toString(){

return $this->name;

}

 

}

$obj=new MyClass("tony");

print

$obj;

?>

14.異常處理

<?php

class

NullHandleException extends Exception{

function __construct($message){

parent::__construct($message);

}

}

function

printObject($obj){

if($obj==null){

throw new NullHandleException("printObject received Null object");

}

Print $obj."<br>";

}

class

MyName{

private $name;

function __construct($name){

$this->name=$name;

}

function __toString(){

return $this->name;

}

}

try

{

printObject(new MyName("bill"));

printObject(null);

printObject(new MyName("Jane"));

 

} catch (NullHandleException $e) {

print $e->getMessage();

print " in file ".$e->getFile()."<br>";

print " on line ".$e->getLine()."<br>";

}

?>

15.在一個PHP文件裏引入另一個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.在函數參數中提示類的類別

<?php

class

ABC{

 

}

class

EFG{

 

}

function

onlyWantObject1($obj){

if(!($obj instanceof ABC)){

die("only Objects of type ABC can be sent to this function");

}

}

function

onlyWantObject2(ABC $obj){

 

}

onlyWantObject1(new EFG());

onlyWantObject2(new EFG());

?>

17.get,set方法

<?php

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=new SetGetClass();

$obj->__set("x", "xxx");

print

$obj->__get("x");

?>

18.

call()具有很多用途。下面的例子顯示如何創建一個授權模型,通過該模型一個HelloWorldDelegator類的實例可以授權所有的方法去調用一個HelloWorld類的實例call_user_func_array()函數允許_call()把它的參數通過call_user_func_array()調用傳遞給world::display(),後者打印3次“Hello world\n”。然後_call()返回$count的值並在屏幕中打印出來。我們不但可以通過_call()方法調用到一個不同的對象(或者用我們想要的方法處理它),而且我們還可以從_call()函數返回值,就像正常的方法一樣。

<?php

class

HelloWorld{

function display($count){

for ($i=0;$i<$count;$i++){

print "Hello World<br>";

}

return $count;

}

}

class

HelloWorldDelegator{

private $obj;

function __construct(){

$this->obj=new HelloWorld();

}

function __call($method,$args){

return call_user_func_array(array($this->obj,$method), $args);

}

}

$obj=new HelloWorldDelegator();

print

$obj->display(3);

?>

19.迭代

<?php

class

HelloWorld{

public $name="John";

public $sex="male";

}

$obj=new HelloWorld();

foreach

($obj as $key=>$value){

print "obj[$key]=$value<br>";

}

 

?>

結果:

obj[name]=John
obj[sex]=male


20.迭代 通過實現Iterator

PHP5可以讓我們用foreach()循環在我們的代碼中重載迭代行爲,使得它按照我們的類的設計執行有實際意義的遍歷。

注意:PHP5不僅可以讓我們重載這種行爲,而且它還可以讓編寫擴展的作者重寫類似的行爲,這已經讓迭代器支持多種PHP擴展,例如SimpleXML和SQite。

   爲了在我們的類中重載迭代器,我們需要執行一些PHP預先定義 的接口。接口如下:

                                        

                                         interface Tracersable

 

 

 

       interface IteratorAggregate        interface Iterator

                                                                          

Iterator getIterator()             void rewind()

                                                                 void next()

                                   bool valid()

                                   mixed key()

                                   mixed current()

 

   任何實現Tracersable接口的類都可以用foreach結構遍歷。但是Tracersable是一個空的接口而且不能直接被執行;反之,我們可以執行Iterator或者IteratorAggregate,他們都是從Tracersable繼承來的。

   主要的接口是Iterator。它定義了我們需要執行的方法以便給我們的類提供foreach迭代的功能。這些方法應該是公共的,如下表:

interface Interator

void rewind()

重新把迭代器指向列表開始處

mixed current()

返回當前位置的值

mixed key()

返回當前位置的關鍵字

void next()

把迭代器移動到下一個關鍵字/值對

bool valid()

返回true/false值,判斷是否有更多的值

例子:

<?php

class

NumberSquared implements Iterator{

private $start,$end;

private $cur;

public function __construct($start,$end){

$this->start=$start;

$this->end=$end;

}

public function rewind(){

$this->cur=$this->start;

}

public function key(){

return $this->cur;

}

public function current(){

return pow($this->cur, 2);

}

public function next(){

$this->cur++;

}

public function valid(){

return $this->cur<=$this->end;

}

}

$obj=new NumberSquared(3, 7);

foreach

($obj as $key=>$value){

print "The square of $key is $value<br>";

}

 

?>

結果:

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.這個代碼的輸出和先前的例子輸出是一樣的。我們可以清楚的看到IteratorAggregate接口可以讓我們把我們的類的主要功能與迭代遍歷它所需要的方法分離到兩個獨立的實體中

<?php

class

NumberSquared implements IteratorAggregate{

private $start,$end;

public function __construct($start,$end){

$this->start=$start;

$this->end=$end;

}

 

public function getIterator(){

return new NumberSquaredIterator($this);

}

public function getStart(){

return $this->start;

}

public function getEnd(){

return $this->end;

}

}

 

class

NumberSquaredIterator implements Iterator{

private $obj;

private $cur;

public function __construct($obj){

$this->obj=$obj;

}

public function rewind(){

$this->cur=$this->obj->getStart();

}

public function key(){

return $this->cur;

}

public function current(){

return pow($this->cur, 2);

}

public function next(){

$this->cur++;

}

public function valid(){

return $this->cur<=$this->obj->getEnd();

}

}

$obj=new NumberSquared(3, 7);

foreach

($obj as $key=>$value){

print "The square of $key is $value<br>";

}

 

?>

22.單例模式

在這個例子中,構造函數和克隆方法都被定義爲private。這麼做的原因是爲了防止開發者用new或者clone運算符錯誤的創建第二個Logger類的實例;因此,getInstance()是唯一可以訪問單件類實例的方法。

<?php

class

Logger{

private function __construct(){}

private function __clone(){}

static private $instance=null;

function Log($str){}

static function getInstance(){

if(self::$instance==null){

self::$instance=new Logger();

}

return self::$instance;

}

}

Logger::getInstance()->Log("check");

 

?>

23.工廠模式

<?php

abstract class

User{

protected $name=null;

function __construct($name){

$this->name=$name;

}

function getName(){

return $this->name;

}

function hasReadPermission(){

return true;

}

function hasModifyPermission(){

return false;

}

function hasDeletePermission(){

return false;

}

function wantsFlashInterface(){

return true;

}

}

class

GuestUvser extends User{

 

}

class

CustomerUser extends User{

function hasModifyPermission(){

return true;

}

}

class

AdminUser extends User{

function hasModifyPermission(){

return true;

}

function hasDeletePermission(){

return true;

}

function wantsFlashInterface(){

return false;

}

}

 

class

UserFactory{

private static $user=array("Andi"=>"admin","stig"=>"guest","Derick"=>"custormer");

static function Create($name){

if(!isset(self::$user[$name])){

print "用戶不存在";

return;

}

switch (self::$user[$name]){

case "guest":

return new GuestUvser($name);

break;

case "customer":

return new CustomerUser($name);

break;

case "admin":

return new AdminUser($name);

break;

}

}

}

function

boolToStr($b){

if($b==true){

return "Yes<br>";

}else{

return "No<br>";

}

}

function

displayPermissions(User $obj){

print $obj->getName()."'s permissions:<br>";

print "Read:".boolToStr($obj->hasReadPermission());

print "<br>";

print "Modify:".boolToStr($obj->hasModifyPermission());

print "<br>";

print "Delete:".boolToStr($obj->hasDeletePermission());

}

function

displayRequirements(User $obj){

if($obj->wantsFlashInterface()){

print $obj->getName()." requires Flash <br>";

}

}

$logins=array("Andi","stig","Derick");

foreach

($logins as $log){

displayPermissions(UserFactory::Create($log));

displayRequirements(UserFactory::Create($log));

}

?>

 24.讀文件

<?php

$filename=fopen("test.php", "r");

do

{

$mychar=fgets($filename,1024);

echo

$mychar;

 

}while(!feof($filename));

fclose($filename);

?>

25.寫文件

<?php

$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 "第二次成功!";

 

}

?>

後面寫的內容會覆蓋前面的

26.寫文件(以寫入方式打開)會追加添加

<?php

$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.指針

<?php

$filename="ddd.txt";

$handle=fopen($filename, "r");

//讀取第一行

$buffer=fgets($handle,1024);

echo

$buffer."<br>";

//讀取第二行

$buffer=fgets($handle,1024);

echo

$buffer."<br>";

//讀取第三行

$buffer=fgets($handle,1024);

echo

$buffer."<br>";

//將指針回到文件開始,繼續讀取第一行數據

rewind($handle);

$buffer=fgets($handle,1024);

echo

$buffer."<br>";

fclose($handle);

?>

28.讀取文件裏的文件名及目錄名

<?php

$dir="D:/Email";

if

(is_dir($dir)){

$dp=opendir($dir);

print_r("目錄已被打開<br>");

while($filen=readdir($dp)){

print_r($filen."<br>");

}

closedir($dp);

}else{

echo "目錄不存在";

}

?>

29.循環讀取目錄

<

table border="1">

<tr>

<th>文件</th>

</tr>

</table>

 

<?php

 

function

direct($dir){

$dp=opendir($dir);

while($filen=readdir($dp)){

if($filen!='.' && $filen!='..'){

$path=$dir."/".$filen;

if(is_dir($path)){

echo "目錄:".$path;

echo "<br>";

direct($path);

}else{

echo "<tr>";

echo "<td>".$path."</td>";

echo "</tr>";

 

}

}

}

}

$dir="D:/TestFolder";

direct(realpath($dir));

 

?>

30.創建目錄

<?php

$dirname="pic";

$str=mkdir($dirname,100);

if

($str){

echo "創建成功";

}

 

?>

 31.格式化當前時間

echo

date('Y m d H:i:s',time());

32.正則表達式

 

$result=preg_match("/love/", "Oh my love");//判斷字符串是否包含love

 

$result=ereg("^Oh", "Oh my love");//判斷字符串首位是不是Oh

$result=ereg("ve$", "Oh my love");//判斷字符串最後是否是ve

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章