PHP面向对象编程

发布时间:2020-06-29 19:09:20 作者:zhuchengdie
来源:网络 阅读:474

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

推荐阅读:
  1. 什么是面向对象编程
  2. PLSQL面向对象编程

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php 面向对象 对象编程

上一篇:如何知道远程的机器是否宕机

下一篇:PostgreSQL 登陆工具pgAdmin以及psql使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》