类方法链式调用的实现

<?php
class Human
{
    private $name = '';
    private $sex  = '';
    private $age  = 0;

    public function __construct()
    {
        // TODO...
    }

    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    public function setSex($sex)
    {
        $this->sex = $sex;
        return $this;
    }

    public function setAge($age)
    {
        $this->age = $age;
        return $this;
    }

    public function printProfile()
    {
        echo "俺叫{$this->name},俺是个{$this->sex},俺今年{$this->age}岁。";
    }
}

$human = new Human();
$human->setName('张三')->setSex('汉子')->setAge(18)->printProfile(); // 输出结果:俺叫张三,俺是个汉子,俺今年18岁。

Copyright © 2023 码农人生. All Rights Reserved