drtj40036 2018-07-25 13:15
浏览 81
已采纳

我们必须在构造函数中声明所有属性吗?

I am new to OOP. Do we have to declare all the properties in constructor? For example:

  private $_conn;
  private $_limit;
  private $_page;
  private $_query;
  private $_total;

public function __construct($conn, $query){

$this->_conn = $conn;
$this->_query = $query;

$rs = $this->_conn->prepare($this->_query);
$rs->execute();
$this->_total = $rs->rowCount();
}

public function getData($page = 1, $limit = 10){

$this->_limit = $limit;
$this->_page  = $page;

if ($this->_limit == 'all'){
    $query = $this->_query;
} else {
    $query = $this->_query." LIMIT ".(($this->_page - 1) * $this->_limit).", $this->_limit";
}
$rs = $this->_conn->prepare($query);
$rs-> execute();

while ($row = $rs->fetch(PDO::FETCH_ASSOC)){
    $results[] = $row;
}

I got this from somewhere on internet. The coder didn't declare $_limit and $_page properties in constructor. Is that for not to create the properties if we don't use the getData method? and can we use this logic for other programming languages like Java, C#, C++?

  • 写回答

3条回答 默认 最新

  • dosin84644 2018-07-25 13:20
    关注

    every method/function (including constructor of the object) should declare only the variables it's going to use.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?