在 Zend Framework 1.12 中,只需使用 getParam() 方法即可。注意 getParam() 的结果是NULL 表示没有可用的键,字符串表示 1 个键,数组表示多个键:
没有“id”值
http://domain.com/module/controller/action/
$id = $this->getRequest()->getParam('id');
// NULL
单个“id”值
http://domain.com/module/controller/action/id/122
$id = $this->getRequest()->getParam('id');
// string(3) "122"
多个“id”值:
http://domain.com/module/controller/action/id/122/id/2584
$id = $this->getRequest()->getParam('id');
// array(2) { [0]=> string(3) "122" [1]=> string(4) "2584" }
如果您总是希望代码中有一个字符串,并且由于某种原因在 url 中设置了更多值,这可能会出现问题:在某些情况下,您可能会遇到错误“数组到字符串转换”。以下是避免此类错误的一些技巧,以确保您始终从 getParam() 获得所需的结果类型:
如果您希望 $id 是一个数组(如果未设置参数,则为 NULL)
$id = $this->getRequest()->getParam('id');
if($id !== null && !is_array($id)) {
$id = array($id);
}
http://domain.com/module/controller/action/
// NULL
http://domain.com/module/controller/action/id/122
// array(1) { [0]=> string(3) "122" }
如果您总是希望 $id 是一个数组(如果未设置则没有 NULL 值,只是空数组):
$id = $this->getRequest()->getParam('id');
if(!is_array($id)) {
if($id === null) {
$id = array();
} else {
$id = array($id);
}
}
http://domain.com/module/controller/action/
// array(0) { }
http://domain.com/module/controller/action/id/122
// array(1) { [0]=> string(3) "122" }
与上面一行相同(无 NULL,始终为数组):
$id = (array)$this->getRequest()->getParam('id');
如果您希望 $id 是一个字符串(第一个可用值,保持 NULL 不变)
$id = $this->getRequest()->getParam('id');
if(is_array($id)) {
$id = array_shift(array_values($id));
}
http://domain.com/module/controller/action/
// NULL
http://domain.com/module/controller/action/122/id/2584
// string(3) "122"
如果您希望 $id 是一个字符串(最后一个可用值,保持 NULL 不变)
$id = $this->getRequest()->getParam('id');
if(is_array($id)) {
$id = array_pop(array_values($id));
}
http://domain.com/module/controller/action/
// NULL
http://domain.com/module/controller/action/122/id/2584/id/52863
// string(5) "52863"
也许有更短/更好的方法来修复 getParam 的这些“响应类型”,但如果您要使用上述脚本,为它创建另一种方法(扩展助手或其他东西)可能会更干净。