>我正在尝试制作一个基本的html表单,该表单将信息传递给php对象,然后将所述对象添加到数组中。 它的工作原理是将信息从表单传递到对象,然后将其添加到数组中并显示所述对象。 但是,当我尝试将第二个对象添加到数组中时,它似乎只是用新的单元素数组替换数组,而不是添加到数组中。 这是我的代码...有什么想法吗?
索引.php文件:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Custom Forms</title>
</head>
<body>
<h2>Add Data</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
<button type="submit" name="submit" value="client">Submit</button>
</form>
<?php
include_once 'clientInfo.php';
include_once 'clientList.php';
if ($_POST) {
$clientArray[] = new clientInfo($_POST["Fname"], $_POST["Lname"]);
}
if (!empty($clientArray)) {
$clientList = new clientList($clientArray);
}
?>
<p><a href="clientList.php">go to client list</a></p>
</body>
</html>
clintInfo.php file:
<?php
class clientInfo {
private$Fname;
private$Lname;
public function clientInfo($F, $L) {
$this->Fname = $F;
$this->Lname = $L;
}
public function __toString() {
return $this->Fname . " " . $this->Lname;
}
}
?>
客户端列表.php文件:
<?php
class clientList {
public function clientList($array) {
foreach($array as $c) {
echo $c;
}
}
}
?>
编辑了带有答案的工作代码
索引.php文件:
<?php
include('clientInfo.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Custom Forms</title>
</head>
<body>
<h2>Add Data</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
<button type="submit" name="submit" value="client">Submit</button>
</form>
<?php
if ($_POST) {
$testClient = new clientInfo($_POST["Fname"], $_POST["Lname"]);
echo $testClient . " was successfully made. <br/>";
$_SESSION['clients'][] = $testClient;
echo end($_SESSION['clients']) . " was added.";
}
?>
<p><a href="clientList.php">go to client list</a></p>
</body>
</html>
客户端列表.php文件:
<?php
include('clientInfo.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>
Accessing session variables
</title>
</head>
<body>
<h1>
Content Page
</h1>
<?php
for ($i = 0; $i < sizeof($_SESSION['clients']); $i++) {
echo $_SESSION['clients'][$i] . " was added. <br/>";
}
?>
<p><a href="index.php">return to add data</a></p>
</body>
</html>
目标文件客户端信息.php保持不变。 对象需要存储在多维 $_SESSION 数组中,并使用 for 循环调用,foreach 循环将不起作用,除非其他人知道使 foreach 循环工作的方法,坚持使用 for。 附带说明一下,可以跳过$testClient变量,同时创建并放置在 $_SESSION 中,但是使用 temp 变量执行此操作可以更轻松地进行故障排除并了解如何使其工作。 只是以为我会发布带有乔希提供的答案的工作代码!
您需要向数组对象添加持久性。
请参阅 PHP 的 _SESSION 美元。
如果不在两次请求之间将其存储到内存或磁盘,则它不可能存在于连续加载中。该链接中有一个很好的教程,应该可以让您启动并运行。
或者,您可以将内容存储在数据库中,以满足更大的需求。