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

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

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条)

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序