PHP链式操作的实现原理

在一个类中有多个方法,当你实例化这个类,并调用多个方法,类似:hello($value)->page('Page Two')->json();

<?php
class hello{
private $value;

public function __construct($value){
$this->value = $value;
}

public function page($title){
$this->value['content'] = $title;
return $this;
}

public function data(){
return $this->value;
}

public function json(){
echo json_encode($this->value);
}

public function html(){
print_r($this->value;)
}
}

写入数据测试一下:

// 测试数据
$value = array('title'=>'Hello world!');

// 链式方法一
$hello = new hello($value);
$hello->page('Page One')->html();

除了上面这种链式样式外,我们在如Lavarel中还会见到下面这种:

// 链式方法二
hello($value)->page('Page Two')->json();

// 增加的代码
function hello($str){
return new hello($str);
}

随机文章:

1、最新实战讲解.htaccess文件rewrite规则
https://www.onexin.net/latest-real-talk-htaccess-file-rewrite-rules/

2、深入理解Magento – 第四章 – Model模型和ORM对象关系映射基础
https://www.onexin.net/depth-understanding-of-magento-chapter-iv-model-based-model-and-orm/

3、Composer手动安装在Windows/Linux/Mac环境中
https://www.onexin.net/composer-install-windows-linux-mac/

4、Fiverr网站5美元服务席卷互联网
https://www.onexin.net/fiverr-5-dollars-web-services-swept-the-internet/

5、随机变换背景图象
https://www.onexin.net/randomly-change-background-image/

转载请注明出处:https://www.onexin.net/php-chain-operation/

Leave a Reply

Your email address will not be published. Required fields are marked *