我正在尝试制作一个基本的 html 表单,将信息传递给 php 对象,然后将所述对象添加到数组中。它的工作原理是将信息从表单传递到对象,然后将其添加到数组中并显示所述对象。但是,当我尝试向数组添加第二个对象时,它似乎只是用新的单元素数组替换数组,而不是添加到它。这是我的代码......有什么想法吗?
index.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 文件:
<?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;
}
}
?>
clientList.php 文件:
<?php
class clientList {
public function clientList($array) {
foreach($array as $c) {
echo $c;
}
}
}
?>
带答案的编辑工作代码
index.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>
clientList.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>
对象文件 clientInfo.php 保持不变。需要将对象存储在多维 $_SESSION 数组中并使用 for 循环调用,foreach 循环将不起作用,除非其他人知道使 foreach 循环工作的方法,坚持使用 for。附带说明一下,可以跳过 $testClient 变量并同时创建并放置在 $_SESSION 中,但是使用 temp 变量可以更容易地排除故障并查看如何使其工作。只是想我会用乔希提供的答案发布工作代码!