我试图做一个基本的HTML表单,将信息传递给一个PHP对象,然后将所述对象添加到数组。它将信息从表单传递到对象,并将其添加到数组并显示所述对象。但是,当我尝试向数组中添加第二个对象时,它似乎只是用一个新的单元素数组替换而不是添加到它。这是我的代码...有什么想法?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;
}
}
}
?>
EDITED工作代码使用答案
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变量来实现,它可以更轻松地排除故障并了解如何使其工作。只是以为我会用Josh提供的答案发布工作代码!
我开始这么想,但是因为我是新人,所以我试图避免它。我会看到我可以将它作为会话变量添加进来。谢谢! – defaultNINJA 2012-08-17 17:12:27
@defaultNINJA:很高兴帮助,祝你好运!由于您在这里似乎是新手,因此请不要忘记通过点击绿色复选标记将您的问题答案标记为正确。这有助于以后找到你的问题的人。 – Josh 2012-08-17 17:12:46
好的会做的!是的,我已经用JAVA和C++编写了一段时间,刚刚得到了我的第一个编程演示,他们想让我做PHP的东西,所以现在我试图将我的OOP技能从JAVA和C++转换为PHP!娱乐时间 :-) – defaultNINJA 2012-08-17 17:16:26