使PHP像js一样链式写法

原文地址:http://bbs.phpchina.com/forum.php?mod=viewthread&tid=237323&reltid=249221&pre_thread_id=0&pre_pos=7&ext=

本人修改了一下,可以再不同类型的对象中进行链式

<?php
class obj{
private $data;
private $name;
private $args;
public $trace=true;  //开启变量跟踪

function __construct($obj){
$this->data=$obj;
}

function __toString(){
if(is_int($this->data))
return (string)$this->data;
return $this->data;
}

public function __call($name,$args){
$this->args=$args;
$this->name=$name;
switch($name){
case 'explode':
array_push($this->args,$this->data);
$this->apply();
break;
case 'implode':
case 'count':
array_push($this->args,$this->data);
$this->data = call_user_func_array($this->name,$this->args);
break;
default:
switch(gettype($this->data)){
case 'array':
array_unshift($this->args,$this->data);
break;
}
$this->apply();
break;
}

if($this->trace){
echo "<pre>";
echo '->'.$this->name;
var_dump($this->data);
echo "-------</pre>";
}
return $this;
}

private function apply(){
switch(gettype($this->data)){
case 'array':
$this->data = call_user_func_array('array_'.$this->name,$this->args);
break;
case 'string':
case 'integer':
$this->data = call_user_func_array($this->name,$this->args);
break;
case 'object':
$this->data = call_user_func_array(array($this->data,$this->name),$this->args);
break;

}
}

}

class t{
function show(){
return "a,b,c";
}
}

//------实例------
$b=new obj(new t());
echo "<pre>";

$t=$b->show()->explode(",")->flip()->implode('|')->explode('|')->count();

// echo($t);

?>

原文地址:https://www.cnblogs.com/vegetbird/p/2864512.html