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、CentOS 8.2 服务器上yum安装Apache+Php+MariaDB+MongoDB
https://www.onexin.net/centos-8-2-yum-apache-php-mariadb-mongodb/

2、Magento升级1.6.0.0 alpha1(笔记)
https://www.onexin.net/magento-upgrade-1-6-0-0-alpha1-notes/

3、CSS 整形与优化工具
https://www.onexin.net/css-shaping-and-optimization-tools/

4、用两句代码实现l图片在网页中的阿尔法效果
https://www.onexin.net/l-with-the-two-pictures-on-the-page-code-to-achieve-the-alpha-effect/

5、Android手机试机指令
https://www.onexin.net/android-phone-test-machine-instruction/

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

Leave a Reply

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