我在php中有这个Task
类:
class Task{
public $title;
public $due_date;
public $priority;
public $course;
public $note;
function __construct($title, $due_date, $priority, $course, $note) {
$this->title = $title;
$this->due_date = $due_date;
$this->priority = $priority;
$this->course = $course;
$this->note = $note;
}
public function is_empty(){
return ($this->title === '' || $this->due_date === '' || $this->priority === '' || $this->course ==='' || $this->note ==='');
}
}
但是当我尝试使用is_empty()
时,它无法正常工作(并且会停止以下所有功能):
//If valid form elements & not a duplicate, add it to data file
if($valid_title && $valid_note && $valid_date){
$task = task_from_form();
//Don't add duplicates or tasks with empty elements
echo "work please"; //prints
$is_empty = $task->is_empty();
echo "$is_empty"; //doesn't print
if(!$is_empty && !in_array($task, $tasks)){
//write task to file
write_file($filename, $task);
//add task to gloabl var tasks
$tasks[] = $task;
}
}
我不确定我制作的语法错误,并且我确定它有些愚蠢,所以任何建议都会非常感谢!
task_from_form()
函数(但我知道这可以使用b / c我之前没有调用$task->is_empty()
使用过它):
//Return task from form elements
function task_from_form(){
if(isset($_POST['submit']) && isset($_POST['title']) && isset($_POST['note'])){
if($_POST['title'] !== '' && $_POST['note'] !== ''){
$title = $_POST['title'];
$note = $_POST['note'];
$title_trim = trim($title);
$note_trim = trim($note);
$title_html = htmlentities($title_trim);
$note_html = htmlentities($note_trim);
$due_date = $_POST['due-date'];
$priority = $_POST['priority'];
$course = $_POST['course'];
$course_space = str_replace("-", " ", $course);
$task = new Task($title_html, $due_date, $priority, $course_space, $note_html);
return $task;
}
}
}
答案 0 :(得分:0)
感谢@MagnusEriksson& @JustOnUnderMillions评论我意识到$task = task_from_form()
正在返回null
,因为return
语句嵌套在if
语句中。因此,如果if
语句未评估为true,则task_from_form()
将返回null。然后我会在null is_empty()
上调用实例方法$task
。所以我在操作is_null($task)
之前使用$task
来检查null。
我还了解了find errors如何使用MAMP!老实说这是b / c的主要问题我在调试之前不知道该怎么做是非常困难的
//If valid form elements & not a duplicate, add it to data file
if($valid_title && $valid_note && $valid_date){
$task = task_from_form();
//Make sure task is not null
if(!is_null($task)){
//Don't add duplicates
if(!$task->is_empty() && !in_array($task, $tasks)){
//write task to file
write_file($filename, $task);
//add task to gloabl var tasks
$tasks[] = $task;
}
}
}