<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP test</title>
</head>
<body>
<?php
/* Class name: Form
 * Description: A class that creates a simple HTML
 * form containing only text input fields
 * The class has 3 methods.
 */
class Form
{
var $fields = array(); #contains field names and labels
var $processor; #name of program to process form
var $submit = "Submit Form";  #value for the submit button
var $Nfield = 0;  #number of fields added to the form /* Constructor: User passes in the name of the script where
 * form data is to be sent($processor) and the value to show 
 * on the submit button.
 */
function __construct($processor, $submit)
{
$this -> processor = $processor;
$this -> submit = $submit;
} /* Display form function. Display the form. */
function displayForm()
{
echo "<form action = '{$this->processor}' method = 'post'>";
echo "<table width='100%'>";
for($j=1; $j<=sizeof($this->fields); $j++)
{
echo "<tr><td align=\"right\">
{$this->fields[$j-1]['label']}: </td>";
echo "<td>
<input type='text'
name = '{$this->fields[$j-1]['name']}'>
</td></tr>";
}
echo "<tr><td colspan=2 align='center'>
<input type='submit'
value='{$this->submit}'></td></tr><br>";
echo "</table>";
} /* Function that adds a field to the form. The user needs
 * to send the name of field and a label to be displyed.
 */
function addField($name, $label)
{
$this->fields[$this->Nfields]['name'] = $name;
$this->fields[$this->Nfields]['label'] = $label;
$this->Nfields = $this->Nfields + 1;
}
}
/* Script name: buildForm
 * Description: uses the form to create a simple HTML form
 */
$phone_form = new Form("process.php", "Submit Phone");
$phone_form -> addField("first_name", "First Name");
$phone_form -> addField("last_name", "Last Name");
$phone_form -> addField("phone", "Phone");
echo "<h3>Please fill out the following form:</h3>";
$phone_form -> displayForm();?>
</body>
</html>输出应该是3个label+一个按钮,但第一行显示为空,值也没传进去,为什么?

解决方案 »

  1.   

    如果var_dump($this->fields)出现array(3) { [""]=> array(2) { ["name"]=> string(10) "first_name" ["label"]=> string(10) "First Name" } [1]=> array(2) { ["name"]=> string(9) "last_name" ["label"]=> string(9) "Last Name" } [2]=> array(2) { ["name"]=> string(5) "phone" ["label"]=> string(5) "Phone" } } 第一个为什么不是0,而是空???
      

  2.   

    声明 var $Nfield = 0;
    使用 $this->fields[$this->Nfields]['name'] = $name;多了或少了个 s