我写了简单的插入数据代码,但每当使用!empty($author)
时,它都会给我这个错误Fatal error: Call to a member function Create() on boolean
但我删除了对!empty($author)
的检查,所以它工作正常。我真的不明白这是给出这个错误以及它的含义。
这是我的代码注释类
class Comment extends DatabaseObject{
// Attributes
protected static $TableName = 'comment';
protected static $DBFields = array('id','author','comment','created','photograph_id');
public $id;
public $author;
public $comment;
public $created;
public $photograph_id;
// Create Comment
public static function Make($photograph_id,$author='Anonymous',$body=''){
if(!empty($photograph_id) && !empty($author) && !empty($body)){
$Comment = new Comment();
$Comment->author = $author;
$Comment->comment = $body;
$Comment->photograph_id = (int)$photograph_id;
$Comment->created = date("Y-m-d H:i:s",time());
return $Comment;
}else{
return FALSE;
}
}
// Find Comment Related Picture
public static function CommentOfPicture($photograph_id){
global $db;
$Comment = static::FindByQuery("SELECT * FROM ".static::$TableName." WHERE `photograph_id`='".$db->EscapeValue($photograph_id)."' ORDER BY created ASC");
return $Comment;
}
}
这是我的表单提交代码
// Comment Submit
if(isset($_POST['submit'])){
$Name = trim($_POST['name']);
$Body = trim($_POST['comment']);
if(!empty($Body) || !empty($Name)){
$Comment = Comment::Make($Photo->id,$Name,$Body);
if($Comment->Create()){
$Session->MSG("Success: Comment is submit, awaiting for approval");
RedirectTo("photo.php?id={$Photo->id}");
}else{
$Session->MSG("Danger: Something is Wrong");
RedirectTo("photo.php?id={$Photo->id}");
}
}else{
$Session->MSG("Danger: Comment is empty");
RedirectTo("photo.php?id={$Photo->id}");
}
}
我认为公共静态函数Make的关系(DatabaseObject)在"Make"方法的结果上调用方法"Create"。如果条件失败,则返回 FALSE。然后,数据库对象调用方法 创建 在 FALSE 上 - 出现错误!如果必须调用 Create 方法,则抛出异常而不是返回 FALSE 或空对象会更好。
你的问题是你的方法签名,
public static function Make($photograph_id,$author='Anonymous',$body='')
默认参数将像这样工作。如果发送string(0) ""
,$author
参数将采用空字符串值而不是'Anonymous'
你几乎没有选择,
要么更改参数的顺序,$author
作为最后一个参数,如果没有提交作者姓名,则使其成为可选参数,或者您可以将空作者姓名替换为'Anonymous'
将其作为类定义中某处的类常量。
另外,这个问题可能会有所帮助。