PHP面向对象编程
1.全局变量
创新互联建站作为成都网站建设公司,专注网站建设公司、网站设计,有关企业网站制作方案、改版、费用等问题,行业涉及成都柔性防护网等多个领域,已为上千家企业服务,得到了客户的尊重与认可。
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.静态方法
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.对象的引用
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.多态
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.多态与继承
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,…{}
与类实现接口类似,一个接口只能继承与自己互相不冲突的接口(也就是说,如果No2定义了No1已经定义的方法或者常量,我们将会收到报错信息)。
?>
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.在一个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.在函数参数中提示类的类别
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()具有很多用途。下面的例子显示如何创建一个授权模型,通过该模型一个HelloWorldDelegator类的实例可以授权所有的方法去调用一个HelloWorld类的实例call_user_func_array()函数允许_call()把它的参数通过call_user_func_array()调用传递给world::display(),后者打印3次“Hello world\n”。然后_call()返回$count的值并在屏幕中打印出来。我们不但可以通过_call()方法调用到一个不同的对象(或者用我们想要的方法处理它),而且我们还可以从_call()函数返回值,就像正常的方法一样。
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
";
}
?>
结果:
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值,判断是否有更多的值 |
例子:
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
";
}
?>
结果:
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接口可以让我们把我们的类的主要功能与迭代遍历它所需要的方法分离到两个独立的实体中
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.单例模式
在这个例子中,构造函数和克隆方法都被定义为private。这么做的原因是为了防止开发者用new或者clone运算符错误的创建第二个Logger类的实例;因此,getInstance()是唯一可以访问单件类实例的方法。
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"第二次成功!";
}
?>
后面写的内容会覆盖前面的
26.写文件(以写入方式打开)会追加添加
$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."
";
//将指针回到文件开始,继续读取第一行数据
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.循环读取目录
<
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.创建目录
$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
网站标题:PHP面向对象编程
文章地址:http://ybzwz.com/article/pigghg.html