2012-03-31 89 views
4
public function process(Zend_Controller_Request_Abstract $request) 
{ 
    $this->first_name = $this->sanitize($request->getPost('first_name')); 
.... 
} 

我的问题是$requestzend_controller_request_abstract类的实例,但的getPost是zend_controller_request_http延伸zend_controller_request_abstract类中定义的函数,那么为什么$request直接调用getPost()

回答

7

类型提示是仅仅是一个暗示。它的全部内容是$request必须从Zend_Controller_Request_Abstract延伸。它确实是而不是的意思是$requestZend_Controller_Request_Abstract的一个实例。

在这种特殊情况下,$requestZend_Controller_Request_Http一个实例,它确实实现getPost(),所以你可以调用$request->getPost()没有问题。 $request也是一个从Zend_Controller_Request_Abstract延伸出来的类的实例,因此PHP允许它首先传递给process方法。

+1

为了扩展这个答案:''instanceof'在这种情况下非常有用,它使您能够测试对象的实际类型 - 如果您不这么做,那么对于不支持getPost的对象()。 – Niko 2012-03-31 15:47:08

0

getPost()Zend_Controller_Request_AbstractZend_Controller_Request_Abstract定义不被任何其他类 的扩展继承了这个功能,因此,在短期,您发布的代码应该抛出一些异常/错误。

编辑:它看起来在PHP中,“如果类或接口被指定为类型提示,那么它的所有子级或实现也被允许。这意味着你可以通过Zend_Controller_Request_HTTPprocess(),它会工作。

来源:http://php.net/manual/en/language.oop5.typehinting.php