php面向对象之链式操作

南笙酒味 提交于 2020-01-02 15:29:59

在一些框架中,比如说thinkphp中,会经常使用

<?php
class index extends Controller{
   public function index(){
      $result = Db::table('think_user')->where('id',1)->find();
   }
}
?>

其中:

//这就是一种链式操作
Db::table('think_user')->where('id',1)->find();

像这种操作如何实现,原理就是在类中的方法中最后要有:


return $this;

例子:

<?php
class StringHelper {
	private $value;
	
	public function __construct($value){
		$this->value = $value;
	}
	
	function getValue($value){
        $this->value = substr($value,0,2);
        //返回$this
        return $this;
    }
 
    function getStrlen() {
        //这里是需要执行的结果,不需要返回$this,
        //如果不是需要执行的解决过,而且还要继续进行链式操作,则需要:return $this;
        return $this->value;
    }
}

$str = new StringHelper("test");
echo $str->getValue('allen')->getStrlen();
?>

如果想要在链接操作中直接使用php的原生函数做为一个功能操作,就需要__call()进行重载。

<?php
class StringHelper {
	private $value;
	
	public function __construct(){
		
	}
	
	public function __call($function,$args){
		$this->value = call_user_func($function, $args[0]);
        return $this;
	}
	
	function getValue(){
        $this->value = substr($this->value,0,2);
        //返回$this
        return $this;
    }
 
    function getStrlen() {
        //这里是需要执行的结果,不需要返回$this,
        //如果不是需要执行的解决过,而且还要继续进行链式操作,则需要:return $this;
        return $this->value;
    }
	
}

$str = new StringHelper();
echo $str->trim('test')->getValue()->getStrlen();

?>

链式操作主要还是简化了书写过程一些不必要的步骤。代码阅读话更容易理解

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!