【发布时间】:2016-05-24 23:10:47
【问题描述】:
在编写 PHP OOP 代码时,为各种类使用“返回对象”以便将成功、失败、错误消息等传递到食物链上,这是一种好的/可接受的/明智的做法吗?
我现在拥有的示例:
“返回对象”:
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 并最终进入 OOP 的正常路线。
【问题讨论】:
-
@ScottWeldon ,注意;仍然在这里学习不同的部分。谢谢
-
@joegrom5 有多个问题与 Programmers 重复:我建议在那里搜索一些好的信息。
-
@ScottWeldon 在引用其他网站时,指出cross-posting is frowned upon 通常会有所帮助
-
@gnat 好点,谢谢。我记下了这一点,这样我以后就不会忘记这样做了。