PipeStyle PHP链式风格

灵感来自使用linux时的 |xargs ,将嵌套函数改为链式风格,意义嘛 来看个例子
$result = abs(round(pow(sin(123),3),1));
》》 0.1
这个是简单的 ,只有四层括号 ,如果需求改了下 四舍五入从保留1位改为保留2位 - - 是不是在数括号了 如果再增加几层呢....


相对而言 如果用管道将结果传递给下个函数 那伪代码是这样的


123 | sin |  pow 参数 3|round 参数 1|abs


这样就清爽多了, 用php的魔术方法实现了下这个风格 代码如下:




class eItem{
    private $oItem;
    public function __construct($obj){
        $obj and $this->oItem = $obj;
        
        return $this;
    }
    public function __destruct(){
        if ($this->oItem ){ unset($this->oItem); }
    }
    public function __toString(){
        return is_string($this->oItem) ? $this->oItem : (string) $this->oItem;
    }
    public function __get($func){
        $this->oItem and $this->oItem = $func($this->oItem );
        return $this;
    }
        public function __call($func , $args){
        
        if ($this->oItem){
            if (empty($args)){
                $this->oItem = $func($this->oItem);
            }else{
                
                $this->oItem = self::_callFunc($func, $args , $this->oItem);
                
            }
        }
        return $this;
    }
    
    private static function _callFunc($func, $args , $oItem){
        !in_array('$' , $args) and array_unshift($args , '$');
         foreach ($args as &$argv){
                    '$' == $argv and $argv = $oItem;
                }
        $argsCount = is_string($func) ? count($args) : 999;
        switch ($argsCount){
            case 1:
                return  $func($args[0]);
                break;
            case 2:
                return  $func($args[0],$args[1]);
                break; 
            case 3:
                return  $func($args[0],$args[1] , $args[2]);
                break;        
            default:
                return  call_user_func_array($func, $args);
        }
            
    }
    public function call($func , $args = null){
        $this->oItem = self::_callFunc($func, (array)$args , $this->oItem);
        return $this;
    }
    
    public function get(){
        return $this->oItem;
    }
}  




DEMO:


$a = new  eItem(123);
$a = $a->sin->pow('$',3)->round(1)->abs->get() ;
$b = abs(round(pow(sin(123),3),1));
var_dump($a , $b);
>> float(0.1)float(0.1)


ps csdn的blog真难用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值