php链式操作,像下面这样:
$test->one()->two()->ok();
如果不使用链式调用时:
<?php
class Test
{
private $value;
public function one($value)
{
$this->value = $value;
}
public function two($value)
{
$this->value .= $value;
}
public function ok()
{
return $this->value;
}
}
$test = new Test();
$test->one('1');
$test->two('2');
echo $test->ok();
?>
使用链式调用时:
<?php
class Test
{
private $value;
public function one($value)
{
$this->value = $value;
return $this;
}
public function two($value)
{
$this->value .= $value;
return $this;
}
public function ok()
{
return $this->value;
}
}
$test = new Test();
echo $test->one('1')->two('2')->ok();
?>
可以看出链式调用更加方便简洁,重点在于每个方法后return $this
,$this
是类的对象;