Php 方法链接get函数以返回特定的$this属性

Php 方法链接get函数以返回特定的$this属性,php,api,class,methods,chaining,Php,Api,Class,Methods,Chaining,我希望能够使用如下对象检索新订单和新发票。我觉得它可读性最好,但我在编写PHP类以这种方式工作时遇到了困难 $amazon = new Amazon(); $amazon->orders('New')->get(); $amazon->invoices('New')->get(); 在我的PHP类中,get()方法如何区分是退回订单还是退回发票 <?php namespace App\Vendors; class Amazon { private $a

我希望能够使用如下对象检索新订单和新发票。我觉得它可读性最好,但我在编写PHP类以这种方式工作时遇到了困难

$amazon = new Amazon();
$amazon->orders('New')->get();
$amazon->invoices('New')->get();
在我的PHP类中,get()方法如何区分是退回订单还是退回发票

<?php

namespace App\Vendors;

class Amazon
{
    private $api_key;
    public $orders;
    public $invoices;

    public function __construct()
    {
        $this->api_key = config('api.key.amazon');
    }

    public function orders($status = null)
    {
        $this->orders = 'orders123';

        return $this;
    }

    public function invoices($status = null)
    {
        $this->invoices = 'invoices123';

        return $this;
    }

    public function get()
    {
        // what is the best way to return order or invoice property
        // when method is chained?
    }

}

由于订单和发票都是设置方法,我建议如下操作:

public function get(array $elements)
{
    $result = [];
    foreach($elements as $element) {
        $result[$element] = $this->$element;
    }

    return $result;
}
因此,您可以按以下方式调用get方法:

$amazon = new Amazon();
$amazon->orders('New')->invoices('New')->get(['orders', 'invoices']);

**您需要在
get
方法中验证元素的可用性。

有两种方法,如果您希望它是动态的,并且不在方法中执行任何逻辑,请使用


你能在这里展示你想要实现的类吗?@PubuduJayawardana补充道
<?php
class Amazon {
    public $type;
    public $method;

    public function get()
    {
        // do logic
        // ...

        return 'Fetching: '.$this->method.' ['.$this->type.']';
    }

    public function __call($method, $type)
    {
        $this->method = $method;
        $this->type = $type[0];

        return $this;
    }

}

$amazon = new Amazon();

echo $amazon->orders('New')->get();
echo $amazon->invoices('New')->get();
<?php
class Amazon {
    public $type;
    public $method;

    public function get()
    {
        return 'Fetching: '.$this->method.' ['.$this->type.']';
    }

    public function orders($type)
    {
        $this->method = 'orders';
        $this->type = $type;

        // do logic
        // ...

        return $this;
    }

    public function invoices($type)
    {
        $this->method = 'invoices';
        $this->type = $type;

        // do logic
        // ...

        return $this;
    }
}

$amazon = new Amazon();

echo $amazon->orders('New')->get();
echo $amazon->invoices('New')->get();