类方法链式调用的实现

<?php

/**
 * Human类
 */
class Human
{
    private string $name = '';
    private string $gender = '';
    private int $age = 0;

    public function setName(string $name): Human
    {
        $this->name = $name;

        return $this;
    }

    public function setGender(string $gender): Human
    {
        $this->gender = $gender;

        return $this;
    }

    public function setAge(int $age): Human
    {
        $this->age = $age;

        return $this;
    }

    public function profile(): void
    {
        echo "俺叫{$this->name}{$this->gender}),今年{$this->age}岁。";
    }
}

$human = new Human();

$human->setName('张三')->setGender('男')->setAge(18)->profile(); // 俺叫张三(男),今年18岁。


//========== 总结 ==========//
// 1、实现链式调用的关键是方法的返回值是类对象本身,也就是$this。



<?php

/**
 * Human类
 */
class Human
{
    private string $name = '';
    private string $gender = '';
    private int $age = 0;

    private static ?Human $instance = null;

    private static function getInstance(): Human
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public static function setName(string $name): Human
    {
        $self = self::getInstance();

        $self->name = $name;

        return $self;
    }

    public static function setGender(string $gender): Human
    {
        $self = self::getInstance();

        $self->gender = $gender;

        return $self;
    }

    public static function setAge(string $age): Human
    {
        $self = self::getInstance();

        $self->age = $age;

        return $self;
    }

    public static function profile(): void
    {
        $self = self::getInstance();

        echo "俺叫{$self->name}{$self->gender}),今年{$self->age}岁。";
    }
}

Human::setName('张三')::setGender('男')::setAge(18)::profile(); // 俺叫张三(男),今年18岁。


//========== 总结 ==========//
// 1、静态方法的链式调用和普通方法的链式调用大同小异,只是需要额外创建一个$instance静态属性来保存类对象,因为普通方法能直接返回$this,
//    但是静态方法不能直接返回self,所以要使用$instance静态属性来模拟$this的效果。

Copyright © 2024 码农人生. All Rights Reserved