简体   繁体   中英

PHP Dynamic Method Chaining

How can I chain multiple methods together without knowing how many there will be? For instance how can I call this addMultiLink method more than once like a loop?

(new EntryField('products'))->addMultiLink($product_ids[0])

Basically I would want the result to be like this:

(new EntryField('products'))->addMultiLink($product_ids[0])->addMultiLink($product_ids[1])->addMultiLink($product_ids[2])

In your addMultiLink return $this :

public function addMultiLink($argument) 
{
    // your code here

    return $this;
}

But as I can see you pass elements of array in your function per call. Maybe it's better to rewrite addMultiLink and consider it's argument as array? Or check if it is array or some integer value:

public function addMultiLink($argument) 
{
    if (is_array($argument)) {
        // do a foreach loop for example
    } else {
        // do something else
    }
}
$product_entry_field = (new EntryField('products'));
    foreach($product_ids as $product_id) {
        $product_entry_field->addMultiLink($product_id);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM