How does the method syntax “public function direct(){}” work in PHP?

三世轮回 提交于 2019-12-06 04:39:22

It is functionality build into Zend Framework.

The $_helpers property in the Controller instance holds an Action_HelperBroker instance. This instance implements PHP's magic __call method. When you call a method that does not exist on that instance, it will try to use the method name to fetch a helper of the same name and call direct() on it (if possible). See code below.

From Zend_Controller_Action

/**
 * Helper Broker to assist in routing help requests to the proper object
 *
 * @var Zend_Controller_Action_HelperBroker
 */
protected $_helper = null;

From Zend_Controller_Action_HelperBroker

/**
 * Method overloading
 *
 * @param  string $method
 * @param  array $args
 * @return mixed
 * @throws Zend_Controller_Action_Exception if helper does not have a direct() method
 */
public function __call($method, $args)
{
    $helper = $this->getHelper($method);
    if (!method_exists($helper, 'direct')) {
        require_once 'Zend/Controller/Action/Exception.php';
        throw new Zend_Controller_Action_Exception('Helper "' . $method . '" does not support overloading via direct()');
    }
    return call_user_func_array(array($helper, 'direct'), $args);
}

The Helper Broker also implement the magic __get method, so when you try to access a property that does not exist, the broker will use the property name as an argument to getHelper()

/**
 * Retrieve helper by name as object property
 *
 * @param  string $name
 * @return Zend_Controller_Action_Helper_Abstract
 */
public function __get($name)
{
    return $this->getHelper($name);
}

Please be aware that magic methods are not meant as a replacement to a proper API. While you can use them as shown above, calling the more verbose

$this->_helper->getHelper('redirector')->gotoSimple('index','index');

is often the much faster alternative.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!