【codeigniter】连贯操作底层原理

php oop连贯操作原理

 

->符号其实是传递对象指针的。或许这么说是不对的。

但是,我们可以这么的理解。

不多说。放代码。

 

普通用法:

<?php

class test

{

  public $a='';

  public $b='';

 

  public function actiona() {

    $this->a="hello";

    return $this;

 

  }

  public function actionb() {

    $this->b="world";

    return $this;

  }

  public function actionc() {

    echo $this->a." ".$this->b;

  }

}

$oktest=new test();

$oktest->actiona();

$oktest->actionb();

$oktest->actionc();

 

?>

 

连贯用法:

<?php

class test

{

  public $a='';

  public $b='';

 

  public function actiona() {

    $this->a="hello";

    return $this;

 

  }

  public function actionb() {

    $this->b="world";

    return $this;

  }

  public function actionc() {

    echo $this->a." ".$this->b;

  }

}

$oktest=new test();

$oktest->actiona()->actionb()->actionc();

?>

 

看到了没有。

连起来了。可以把操作串起来。

看起来直观多了。阅读代码时也轻松了很多。

 

类里面操作都返回了一个指针。

$this.

他等价于你初始化的那个对象 $oktest

所以下面的操作可以连续起来。

 

试着去掉每个操作里的return $this

你将会看到错误提示。

 

原文地址:http://www.phpchina.com/index.php?action-viewthread-tid-103114

例子:


<?php

class sql{

 

 public $select;

 public $from;

 public $where;

 public $order;

 public $limit;

 

 public function from($_from='FROM test') {

  $this->from=$_from;

  return $this;

 }

 

 public function where($_where='WHERE 1=1') {

  $this->where=$_where;

  return $this;

 }

 

 public function order($_order='ORDER BY id DESC') {

  $this->order=$_order;

  return $this;

 }

 

 public function limit($_limit='LIMIT 0,30') {

  $this->limit=$_limit;

  return $this;

 }

 

 public function select($_select='SELECT *') {

  $this->select=$_select;

  return $this->select." ".$this->from." ".$this->where." ".$this->order." ".$this->limit;

 }

 

}

 

$sql =new sql();

 

echo $sql->from()->where()->order()->limit()->select();

 

?>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值