PHP方法链-反映了吗? [英] PHP Method Chains - Reflecting?

查看:48
本文介绍了PHP方法链-反映了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对方法调用链进行反思,以确定您在调用链中的哪一点? 至少,是否有可能辨别某个方法是否是链中的最后一个调用?

Is it possible to reflect upon a chain of method calls to determine at what point you are in the chain of calls? At the very least, is it possible to discern whether a method is the last call in the chain?

$instance->method1()->method2()->method3()->method4()

是否可以使用返回对象实例的属性来做同样的事情?

Is it possible to do the same using properties that return instances of objects?

$instances->property1->property2->property3->property4

推荐答案

如果您正在调用的所有方法都返回 same 对象以创建流畅的界面(与将不同的对象链接在一起相反) ),将方法调用记录在对象本身中应该是很简单的.

If all the methods you're calling are returning the same object to create the fluent interface (as opposed to chaining different objects together), it should be fairly trivial to record the method calls in the object itself.

例如:

class Eg {
    protected $_callStack = array();

    public function f1()
    {
        $this->_callStack[] = __METHOD__;
        // other work
    }

    public function f2()
    {
        $this->_callStack[] = __METHOD__;
        // other work
    }

    public function getCallStack()
    {
        return $this->_callStack;
    }
}

然后像这样将通话链接起来

Then chaining the calls like

$a = new Eg;
$a->f1()->f2()->f1();

将像这样离开调用堆栈: array('f1','f2','f1');

would leave the call stack like: array('f1', 'f2', 'f1');

这篇关于PHP方法链-反映了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆