当编写PHP面向对象的代码时,使用“返回对象”来传递成功、失败、错误信息等是否是一种好的/可接受的/明智的做法?
以下是我现在的示例: “返回对象”:
以下是我现在的示例: “返回对象”:
class JsqlReturn{
public $response;
public $success;
public $debug_message;
public $mysqli_result_obj;
function __construct($bool=false,$debug_message=NULL,$res=NULL,$mysqli_result_obj=NULL){
$this->success = $bool;
$this->response = $res;
$this->debug_message = $debug_message;
$this->mysqli_result_obj = $mysqli_result_obj;
}
}
包含示例方法的主类:
class Jsql{
function connect($host,$username,$password,$database){ #protected?
$this->db = new \mysqli($host,$username,$password,$database);
if($this->db->connect_errno){
return new JsqlReturn(false,"Connection failed: (".$this->db->connect_errno.") ".$this->db->connect_error);
}
else{
return new JsqlReturn(true,NULL,"Connection success.");
}
}
}
实施:
$db = new Jsql;
$return = $db->connect(...);
if($return->success){ echo $return->response; }
else{ echo $return->debug_message; }
我知道在这里使用一个连接示例是琐碎的,但我的问题与编码实践有关。
我的主要目标是确保我在处理方法返回数据时保持一致的方式。
注:请多多包涵,这是我在这里的第一个问题。 :) 我一直在自学,从几年前尝试HTML开始,转向过程式PHP,最终进入面向对象编程。