首页 > 【PHP】return $this

【PHP】return $this

Laravel里很多 return $this

着实不明白这是什么原理,百度后发现如下比较好的解释:

class sum
{
    private $num1;
    private $num2;

    public function num1($n)
    {
        $this->num1 =$n;
        return $this;
    }

    public function num2($n)
    {
        $this->num2=$n;
        return $this;
    }

    public function sum()
    {
        return $this->num1+$this->num2;
    }
}

$sum=new sum();
$sum->num1(10)->num2(5)->sum();

三个疑问:
1、
既然num1和num2的设计初衷是方法,为什么开头却要变成它的属性私有呢?

private $num1;
private $num2;
...num1($n)
...num2($n)

2、
$this->num1 = $n

自身的参数值($n)赋值给自身的方法($num1),这是什么原理?有什么用呢?

3、
return $this 这什么技巧,在larval里利用率太高了,脑子转不过来。

可能深夜了,问题太多,脑子很糊,谢谢解答,为感!

睡醒再来看来,真的摸索不出来


1、属性设计为私有是防止外部直接通过属性赋值来修改其值。只有通过暴露的公用方法来赋值。

2、对类的属性进行赋值操作。

3、实现环形调用。$sum->num1(10) 对 $sum 对象的num1进行赋值,执行完成后返回结果是当前 $sum 对象,然后再调用 num2(5) 方法对num2 进行复制,同时返回当前的$sum 对象,最后调用 $sum 对象的sum方法。


举个栗子:

$object = new ClassName();

$object->method1();
$object->method2();
$object->method3();

这种方法想写成:

$object->method1()->method2()->method3();

那么 method1,method2,method2 里就必需返回 $object,在 method* $object 是什么?就是 $this 啊。

现在你看看,method1 里面为什么会有 method2 方法,因为 method1 返回了 $object 啊!


返回this可以实现类似于JavaScript的链式调用


链式操作,具体应用场景像这样

/*
 * SQL语句组合实例类,始发文章web开发笔记
 * 学习用,非专业类
 * */
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
【热门文章】
【热门文章】