为什么这个PHP变量不会按请求递增?

时间:2017-08-24 20:23:28

标签: php

每次提交新表单时,回复$numOfEmployees始终相同。我在这做错了什么?我每次尝试将它保存到会话中但仍然无法正常工作。我是PHP的新手,到目前为止还不是最大的粉丝...

<?php

class Employee{

    private $fn;
    private $ln;
    private $dpt;
    private $ID;

    public function setVars($fna, $lna, $dpta, $numOfEmployeesa){
        $this-> fn = $fna;
        $this -> ln = $lna;
        $this -> dpt = $dpta;
        $this -> ID = $numOfEmployeesa;
    }

}
if(isset($_SESSION['numOfEmployees'])){
    //get it
    $numOfEmployees = $_SESSION['numOfEmployees'];
} else {
    //set a default value if not isset
    $numOfEmployees = 0;
}
if(isset($_SESSION['employeeArray'])){
    //get it
    $employeeArray = $_SESSION['employeeArray'];
} else {
    //set a default value if not isset
    $employeeArray = array();
}

$employee = new Employee();
$fn = $_POST['firstname'];
$ln = $_POST['lastname'];
$dpt = $_POST['department'];

$employee -> setVars($fn, $ln, $dpt, $numOfEmployees);

$numOfEmployees++;

echo "First Name: " . $fn . "\nLast Name: " . $ln . "\nDepartment: " . $dpt . "\nID: " . sprintf('%08d', $numOfEmployees) . "\nNumber of employees: " . $numOfEmployees;

$employeeArray[] = $employee;

$_SESSION['employeeArray'] = $employeeArray;
$_SESSION['numOfEmployees'] = $numOfEmployees;

?>

1 个答案:

答案 0 :(得分:0)

尝试在文件开头添加session_start()