溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PHP面向?qū)ο缶幊?/h1>
發(fā)布時(shí)間:2020-06-29 19:09:20 來源:網(wǎng)絡(luò) 閱讀:469 作者:zhuchengdie 欄目:web開發(fā)

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.靜態(tài)方法

<?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.對(duì)象的引用

<?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.多態(tài)

<?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.多態(tài)與繼承

<?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,…{}

與類實(shí)現(xiàn)接口類似,一個(gè)接口只能繼承與自己互相不沖突的接口(也就是說,如果No2定義了No1已經(jīng)定義的方法或者常量,我們將會(huì)收到報(bào)錯(cuò)信息)。

?>

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.在一個(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ù)中提示類的類別

<?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()具有很多用途。下面的例子顯示如何創(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ù)返回值,就像正常的方法一樣。

<?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>";

}

 

?>

結(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值,判斷是否有更多的值

例子:

<?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>";

}

 

?>

結(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í)體中

<?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.單例模式

在這個(gè)例子中,構(gòu)造函數(shù)和克隆方法都被定義為private。這么做的原因是為了防止開發(fā)者用new或者clone運(yùn)算符錯(cuò)誤的創(chuàng)建第二個(gè)Logger類的實(shí)例;因此,getInstance()是唯一可以訪問單件類實(shí)例的方法。

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

 

}

?>

后面寫的內(nèi)容會(huì)覆蓋前面的

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

<?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>";

//將指針回到文件開始,繼續(xù)讀取第一行數(shù)據(jù)

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.循環(huán)讀取目錄

<

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.創(chuàng)建目錄

<?php

$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

向AI問一下細(xì)節(jié)
AI