[英]Use a Callback on PHP chained methods
Let's say you have a class like:假设你有一个类:
class Foo
{
// maybe private or protected?
public Pages $pages;
public Owners $owners;
// ...
}
How can I implement methods that would accept closures in a chained fashion?如何实现以链式方式接受闭包的方法? Every method call in the chain should update the internal class properties (so they are using the latest).
链中的每个方法调用都应该更新内部类属性(因此它们使用最新的)。
Usage examples:用法示例:
$pagesArray = Foo::wherePage('page', function ($page, $owners) {
// do something with the given page, owners is optional
})->b(function ($owners) {
// now do something with owners, e.g. $owners->foo();
})->getPagesArray();
Or或者
$pagesArray = Foo::pages(function ($pages, $owners) {
// loop pages, owners is optional
})->b(function ($owners) {
// now do something with owners, e.g. $owners->foo();
})->getPagesArray();
Thanks!谢谢!
<?php
class Foo
{
protected $pages = ['abc'];
public static function setPages($pages)
{
call_user_func($pages, ['aaa']);
$thisClass = new static();
return $thisClass;
}
public function owners($owners)
{
call_user_func($owners, ['john', 'wick']);
return $this;
}
public function getPages()
{
return $this->pages;
}
}
$Foo = Foo::setPages(function($pages) {
var_dump($pages);
})->owners(function($owners) {
var_dump($owners);
})->getPages();
var_dump($Foo);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.