<!doctype html>
<html>
<head>
<title>Index</title>
</head>
<form action="newquestion.php" method="post">
Question <input type="text" name="question">
<input type="submit">
</form>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
PHP文件......
<?php
static $q = 1;
echo $q;
$q++;
?>
Run Code Online (Sandbox Code Playgroud)
我是PHP的新手.每次调用"newquestion.php"时,这不会增加$ q吗?如果不是每次调用或打开此页面(newquestion.php)时如何增加此变量?
不,因为$q每次调用页面时重置为1.您需要某种持久性策略(数据库,写入文本文件等)以跟踪页面视图.
将此功能合并到一个类中也是一个好主意,该类可以在您的代码库中使用.例如:
class VisiterCounter {
public static function incrementPageVisits($page){
/*!
* Beyond the scope of this question, but would
* probably involve updating a DB table or
* writing to a text file
*/
echo "incrementing count for ", $page;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在newquestion.php中,
VisiterCounter::incrementPageVisits('newquestion.php');
Run Code Online (Sandbox Code Playgroud)
或者,如果您有一个前端控制器来处理Web应用程序中的所有请求:
VisiterCounter::incrementPageVisits($_SERVER['REQUEST_URI']);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5752 次 |
| 最近记录: |