当前位置: 首页 > 后端技术 > PHP

php语言特性学习(三)

时间:2023-03-29 23:13:59 PHP

1.__get__setclassTest{private$arr=array('x'=>null,'y'=>null);函数__get($property){if(array_key_exists($property,$this->arr)){return$this->arr[$property];}else{print"error:cannotreadthispropertyisnotexistthanxory\n";}}函数__set($property,$value){if(array_key_exists($property,$this->arr)){$this->arr[$property]=$value;}else{print"error:cannotwritethispropertyisnotexistthanxory\n";}}}$cl=newTest();$cl->x=1;echo$cl->x;$cl->t=2;echo$cl->t;//结果是1error:cannotwrite此属性除x或y错误外不存在:无法读取此属性除x或y2外不存在时间;$i++){打印“你好世界\n”;}}}classcallHelloWorld{private$obj;函数__construct(){$this->obj=newHelloWorld();}function__call($method,$arg){returncall_user_func_array(array($this->obj,$method),$arg);}}$me=newcallHelloWorld();$me->display(3);结果是helloworldhelloworldhelloworld3.代器classnumberSquareimplementsIterator{private$start;私人$结束;私人$cur;公共函数__construct($start,$end){$this->start=$start;$this->end=$end;}publicfunctionrewind(){$this->cur=$this->start;}publicfunctionkey(){return$this->cur;}publicfunctioncurrent(){returnpow($this->cur,3);}publicfunctionnext(){$this->cur++;}publicfunctionvalid(){return$this->cur<=$this->end;}}$obj=newnumberSquare(2,5);foreach($objas$key=>$value){print"the$key的平方是$value
\n";}结果是2的平方是83的平方是274的平方是645的平方是1254.工厂模式//DefineabstractclassUser类读取、修改和删除权限未赋予抽象类User{private$name=null;function__construct($name){$this->name=$name;}functiongetName(){return$this->name;}//权限方法functionhasReadPermission(){returntrue;}functionhasModifyPermission(){returnfalse;}functionhasDeletePermission(){returnfalse;}//自定义方法functionwantsFlsahInterFace(){returntrue;}}classGuestUserextendsUser{}classCustomerUserextendsUser{//客户有修改权限wantsFlsahInterFace(){返回错误的;}}classUserFactory{privatestatic$users=array("andy"=>'Admin',"tom"=>'customer',"jack"=>'guest');staticfunctioncreate($name){switch(self::$users[$name]){case'Admin':returnnewAdminUser($name);休息;case'customer':returnnewCustomerUser($name);休息;case'guest':returnnewGuestUser($name);休息;默认值:中断;}}}functionboolToString($b){if($b==true){返回“是”;}else{返回“否”;}}functiondisplayPermission($obj){打印$obj->getName()。"的权限:\n";打印“阅读:”。boolToString($obj->hasReadPermission());打印“修改:”。boolToString($obj->hasModifyPermission());打印“删除:”。boolToString($obj->hasDeletePermission());}functiondisplayRequirement($obj){if($obj->wantsFlsahInterFace()){print$obj->getName().“需要闪光灯\n”;}}$login=array("andy",'str','jack');foreach($loginas$key=>$val){displayPermission(UserFactory::create($val));}收到结果updatedreceivedupdated//不会有任何实例化,直到有事件或设置了参数,才会有任何输出。一开始有一个继承观察类的观察类实现类,在初始化的时候实例化实现类中改变值的类。当有值变化时,调用实现类的方法继承观察类(即完成通知)。在方法中可以写出收到通知后的操作,比如打印字符串等。5.观察者模式**给程序员一个鼓励!**微信支付宝