行“return $something;” 将停止代码执行并返回值。如果要返回多个值,则需要返回一个数组或使用两个单独的函数来返回这些值。如果你想返回一个数组,你可以这样做:
public function rememberLastProductSearched() {
$returnArray = array();
$session = new Zend_Session_Namespace(searchedproducts);
if ($this->getRequest()->getParam('product-searched')) {
$session->ProductSearched = $this->getRequest()->getParam('product-searched');
$returnArray['productSearched'] = $session->ProductSearched;
} else {
if ($session->ProductSearched) {
$returnArray['productSearched'] = $session->ProductSearched;
}
}
if ($this->getRequest()->getParam('search-term')) {
$session->SearchTerm = $this->getRequest()->getParam('search-term');
$returnArray['searchTerm'] = $session->SearchTerm;
} else {
if ($session->SearchTerm) {
$returnArray['searchTerm'] = $session->SearchTerm;
}
}
return $returnArray;
}
在您的控制器或您想要检查这些值的任何地方:
$lastSearch = $this->rememberLastProductSearched();
echo $lastSearch['productSearched']; // Product Searched
echo $lastSearch['searchTerm']; // Search terms
但是使用两个功能可能更干净
public function getLastProductSearched() {
$session = new Zend_Session_Namespace(searchedproducts);
if ($this->getRequest()->getParam('product-searched')) {
$session->ProductSearched = $this->getRequest()->getParam('product-searched');
$returnValue = $session->ProductSearched;
} else {
if ($session->ProductSearched) {
$returnValue = $session->ProductSearched;
}
}
return $returnValue;
}
public function getLastSearchTerms() {
$session = new Zend_Session_Namespace(searchedproducts);
if ($this->getRequest()->getParam('search-term')) {
$session->SearchTerm= $this->getRequest()->getParam('search-term');
$returnValue = $session->SearchTerm;
} else {
if ($session->SearchTerm) {
$returnValue = $session->SearchTerm;
}
}
return $returnValue;
}
你可以像这样使用它们:
echo $this->getLastProductSearched(); // Product Searched
echo $this->getLastSearchTerms(); // Search terms
这将使您的代码在以后更易于阅读和调试。关于您的代码的更多注释。您可以通过使用 || 来避免使用嵌套的 if。
if ($this->getRequest()->getParam('product-searched') || $session->ProductSearched) {
$returnValue = $this->getRequest()->getParam('product-searched') || $session->ProductSearched;
}
将实现相同的目标:
if ($this->getRequest()->getParam('product-searched')) {
$session->ProductSearched = $this->getRequest()->getParam('product-searched');
$returnArray['productSearched'] = $session->ProductSearched;
} else {
if ($session->ProductSearched) {
$returnArray['productSearched'] = $session->ProductSearched;
}
}
希望这可以帮助 !