我将此工作示例代码作为示例...
function get_childs() {
$array = array(1 => 'item1', 2 => 'item2', 3 => 'item3');
return $array;
}
function add( $array, $item ) {
$array[] = $item;
return $array;
}
function array_delete( $array, $key ) {
unset( $array[$key] );
return $array;
}
$result_array = array_delete( add( get_childs(), 'test' ), 2 );
print_r( $result_array );
改为箭头
现在,代码的一部分看起来像这样(非常难看):
array_delete( add( get_childs(), 'test' ), 2 );
我在网上看到有可能这样做:
get_childs().add('test').delete(2);
更美丽。 如何完成?
旁注
我已经看到这样调用的函数可以像这样重复:
get_childs().add('something1').add('something2').add('something3');
答案 0 :(得分:4)
最简单的方法是将此功能移至课程,例如:
class MyCollection
{
private $arr;
public function create_childs()
{
$this->arr = array(1 => 'item1', 2 => 'item2', 3 => 'item3');
return $this;
}
public function get_childs()
{
return $this->arr;
}
public function add($item)
{
$this->arr[] = $item;
return $this;
}
public function delete($key)
{
unset($this->arr[$key]);
return $this;
}
}
$collection = new MyCollection();
print_r($collection->create_childs()->add("test")->delete(2)->get_childs());