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、Wordpress整合Ucenter最简单的实现方法
https://www.onexin.net/wordpress/wordpress-integration-of-the-most-simple-implementation-ucenter/

2、centos5.2安装+apache+php+mysql+gd+zend+phpmyadmin
https://www.onexin.net/solution/apache/centos5-2-e5-ae-89-e8-a3-85apachephpmysqlgdzendphpmyadmin/

3、[视频教程]教菜鸟一分钟学会做动态的88*31的网站链接LOGO
https://www.onexin.net/latest/video-tutorial-to-teach-the-rookie-one-minutes-learn-how-to-do-dynamic-88-31-links-to-websites-logo/

4、为什么选择Magento开源网店系统?
https://www.onexin.net/resource/why-magento-open-source-online-store-system/

5、如何提高网站的PageRank值?
https://www.onexin.net/programming/how-to-improve-the-sites-pagerank-values/

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

Leave a Reply

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