zoukankan      html  css  js  c++  java
  • PHP中的连贯操作

    连贯操作有什么好处?就是多行操作可以在一行之内完成,要进行连贯操作的方法必须返回$this,也就是当前类的对象实例,然后就可以进行连贯操作了,具体的实现代码如下所示。
     1 <?php
     2 /**
     3  * php的连贯操作功能
     4  * @date 2016.3.31
     5  */
     6 namespace advanced;
     7 class Join {
     8     //姓名
     9     private $name;
    10 
    11     //性别
    12     private $sex;
    13 
    14     //身高
    15     private $height;
    16 
    17     private $data = array();
    18 
    19     public function __construct($info = array()) {
    20         if (isset($info['name']) && !is_null($info['name'])) $this->name = $info['name'];
    21         if (isset($info['sex']) && !is_null($info['sex'])) $this->sex = $info['sex'];
    22         if (isset($info['height']) && !is_null($info['height'])) $this->height = $info['height'];
    23 
    24         return $this;
    25     }
    26 
    27     /**
    28      * 要进行连贯操作的方法必须返回$this,也就是当前类的对象实例,然后就可以进行连贯操作了
    29      * @return advancedJoin
    30      */
    31     public function formatInfo() {
    32         foreach (get_object_vars($this) as $key => $val) {
    33             if ($key == 'data') continue;
    34             
    35             $this->data[$key] = $val;
    36         }
    37 
    38         return $this;
    39     }
    40 
    41     public function getUserInfo() {
    42         return implode(', ', $this->data);
    43     }
    44 }
    45 /*
    46 如果这样连贯操作,$data = new advancedJoin(array('name' => 'mayun', 'sex' => 'male', 'height' => '170'))->formatInfo()->getUserInfo();
    47 会报如下的错误
    48 Parse error: syntax error, unexpected T_OBJECT_OPERATOR
    49 */
    50 $join = new advancedJoin(array('name' => 'mayun', 'sex' => 'male', 'height' => '170'));
    51 $data = $join->formatInfo()->getUserInfo();
    52 echo $data;
    53 ?>

    运行join.php

    输出mayun, male, 170

  • 相关阅读:
    centos 安装 TortoiseSVN svn 客户端
    linux 定时任务 日志记录
    centos6.5 安装PHP7.0支持nginx
    linux root 用户 定时任务添加
    composer 一些使用说明
    laravel cookie写入
    laravel composer 安装指定版本以及基本的配置
    mysql 删除重复记录语句
    linux php redis 扩展安装
    linux php 安装 memcache 扩展
  • 原文地址:https://www.cnblogs.com/caihuafeng/p/5341950.html
Copyright © 2011-2022 走看看