【发布时间】:2014-01-12 13:57:38
【问题描述】:
我收到了错误
PHP Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 33292313 bytes)
当我运行分页功能时,我不知道发生了什么和/或为什么会出现错误。
根据我在这里看到的其他问题,大多数人建议我更改 php.ini 文件中的内存限制。但是,我想知道为什么会发生此错误以及我可以做些什么来防止它会在未来发生。
从这个问题Meaning of "Fatal error: Allowed memory size of x bytes exhausted (tried to allocate y bytes)"? 我可以看到 php 脚本已经超出了分配的内存限制(呃!)但它并没有真正的帮助。
问题:
- php 不就是一种与数据库交互的语言吗?那为什么它需要内存才能运行呢?
- 什么原因导致错误?(我知道内存不够,但为什么内存用完这么多)
- 我能做些什么来防止它再次发生
我的分页功能:
function Pagination( $connection, $num, $page, $view ) {
$view=$view;
//Results per page
$pagerows=10;
//Tells us the last page number
$last=ceil( $num/$pagerows );
// Establish the $PaginationNav variable(used to navigate the paginated results)
$PaginationNav = '';
//Check how many pages of results there are
//If there is more than 1 page
if( $last != 1 ) {
//Check if we are on page 1, if so we don't need the 'previous' link
//We are on page one
if( $page == 1 ) {
//Adds the current page
$PaginationNav .= $page;
//Adds the next 3 pages to the pagination
for( $i=$page+1;$i<$last;$i++ ) {
$PaginationNav .= "<a class='Pagination' href=\"$_SERVER[PHP_SELF]?view=$view&page=$i\">$i</a>";
if( $i > $page+4 ) {
break;
}
}
$PaginationNav .= "...";
//Adds the last page to the pagination
$PaginationNav .= "<a class='Pagination' href=\"$_SERVER[PHP_SELF]?view=$view&page=$last\">$last</a>";
//Adds the next page button
$next=$page + 1;
$PaginationNav .= "<a class='Pagination' href=\"$_SERVER[PHP_SELF]?view=$view&page=$next\">Next </a> ";
} else {
//we are not on page 1
//Adds the previous button to pagination
$previous=$page - 1;
$PaginationNav .= "<a class='Pagination' href=\"$_SERVER[PHP_SELF]?view=$view&page=$previous\">Previous</a>";
//Adds the current page
$PaginationNav .=$page;
//Adds the left navigations
for( $i = $page-4;$i=$page;$i++ ) {
if( $i>0 ) {
$PaginationNav .= "<a class='Pagination' href=\"$_SERVER[PHP_SELF]?view=$view&page=$i\">$i</a>";
}
}
//Adds the right navigations
for( $i=$page;$i<$last;$i++ ) {
$PaginationNav .= "<a class='Pagination' href=\"$_SERVER[PHP_SELF]?view=$view&page=$i\">$i</a>";
if( $i > $page+4 ) {
break;
}
}
//Adds the last page to the pagination
$PaginationNav .= "<a class='Pagination' href=\"$_SERVER[PHP_SELF]?view=$view&page=$last\">... $last</a>";
//Adds the next page button
$next=$page + 1;
$PaginationNav .= "<a class='Pagination' href=\"$_SERVER[PHP_SELF]?view=$view&page=$next\">Next </a> ";
}
}
//There is only one page
if( $last == 1 ) {
$PaginationNav .= $page;
}
return $PaginationNav;
}
对我看到的一个问题有评论指出,简单地增加内存限制并不能很好地替代良好的编码。我同意,并且我想将代码更改为更好,而不是简单地盲目增加内存。
P.S 我没有接受过正式的编程培训,我只是通过全身心地投入到编码中来学习,所以如果答案很明显,我很抱歉。
【问题讨论】:
-
$view = $view- 这条线的目的是什么?另外,错误在哪一行?
标签: php memory memory-management