php调用id代码怎么写,php链式操作的实现

php链式操作的关键是在做完操作后要return $this;

一、不使用__call方法实现链式操作

class Sql{

private $sql=array("from"=>"",

"where"=>"",

"order"=>"",

"limit"=>"");

public function from($tableName) {

$this->sql["from"]="FROM ".$tableName;

return $this;

}

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

$this->sql["where"]="WHERE ".$_where;

return $this;

}

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

$this->sql["order"]="ORDER BY ".$_order;

return $this;

}

public function limit($_limit='30') {

$this->sql["limit"]="LIMIT 0,".$_limit;

return $this;

}

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

return "SELECT ".$_select." ".(implode(" ",$this->sql));

}

}

$sql =new Sql();

echo $sql->from("testTable")->where("id=1")->order("id DESC")->limit(10)->select();

//输出 SELECT * FROM testTable WHERE id=1 ORDER BY id DESC LIMIT 0,10

?>

二、使用__call方法实现链式操作

__call()在对象调用一个不可访问的方法时会被触发,所以可以实现类的动态方法的创建,实现php的方法重载功能,但它其实是一个语法糖(__construct()方法也是)。

class String

{

public $value;

public function __construct($str=null)

{

$this->value = $str;

}

public function __call($name, $args)

{

$this->value = call_user_func($name, $this->value, $args[0]);

return $this;

}

public function strlen()

{

return strlen($this->value);

}

}

$str = new String('01389');

echo $str->trim('0')->strlen();

// 输出结果为 4;trim('0')后$str为"1389"

?>

以上内容希望帮助到大家,更多PHP大厂PDF面试文档,PHP进阶架构视频资料,PHP精彩好文免费获取可以微信搜索关注公众号:PHP开源社区,或者访问:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值