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 \advanced\Join
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 \advanced\Join(array('name' => 'mayun', 'sex' => 'male', 'height' => '170'))->formatInfo()->getUserInfo();
47 会报如下的错误
48 Parse error: syntax error, unexpected T_OBJECT_OPERATOR
49 */
50 $join = new \advanced\Join(array('name' => 'mayun', 'sex' => 'male', 'height' => '170'));
51 $data = $join->formatInfo()->getUserInfo();
52 echo $data;
53 ?>

运行join.php

输出mayun, male, 170