为什么简单的布尔php实例函数不起作用? 问题
我有一个php中的为什么简单的布尔php实例函数不起作用? 问题,php,Php,我有一个php中的任务类: 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; $th
任务类:
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()
时,它不起作用(&停止下面的所有功能):
我不确定我犯了什么语法错误,我肯定这是愚蠢的,所以任何建议都将不胜感激
代码
函数的task\u from\u form()
是空的(但我知道这是有效的,因为我以前使用过它,但没有调用$task->is\u empty()
):
多亏了@MagnusEriksson&@JustOnUnderMillowns注释,我意识到来自表单()的$task=task\u正在返回null
,因为return
语句嵌套在if
语句中。因此,如果if
语句的计算结果不是true,则task\u from\u form()
将返回null。然后我将调用null$task
上的实例方法is_empty()
。因此,在操作$task
之前,我使用is\u null($task)
检查null
我还发现了如何使用MAMP!老实说,这是b/c的主要问题,我以前不知道怎么做,所以调试相当困难
固定代码
“我不确定发生了什么语法错误…”第一步调试时,检查错误日志中是否有正确的错误消息。它显示了一些错误消息?您期望的是什么,出了什么问题?可能是task\u from\u form()
中的if语句没有验证为true,因此没有返回类的实例,稍后您将尝试使用它。如果函数返回null而不是类,则:$task->is_empty()
将中断代码instance@MagnusEriksson我在哪里可以看到这个错误日志?我使用括号作为我的文本编辑器和MAMP来查看我的网站,我在Chrome上查看
//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;
}
}
//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;
}
}
}
//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;
}
}
}