的getter和setter調用的數量這可能是一個愚蠢的問題,但我無法弄清楚google是什麼。我正在學習面向對象,並得到一般概念,但試圖實現它,我收到一些問題。減少來自類
我正在使用簡單的html dom製作網絡抓取工具。我想創建一個連接到一個頁面的類,並且包含我可以在該頁面上調用的幾個不同的函數,具體取決於我想要執行的操作。然後我可以從另一個文件調用這個類的方法。
這是我寫的類:
<?php
include_once '/simple_html_dom.php';
class CountyScraping
{
protected $demoMode = 0; //set 1 for demo
protected $cinemas = NULL;
protected $url = NULL;
protected $html = NULL;
protected $counties = array();
function __construct($url)
{
$this->setUrl($url);
}
public function setUrl($url)
{
$this->url = $url;
}
public function getUrl()
{
return $this->url;
}
public function setHtml()
{
$this->html = file_get_html($this->url);
}
public function getHtml()
{
return $this->html;
}
public function setCounties()
{
foreach($this->html->find('#UserLocation option') as $element)
{
if (($element->value != NULL) && ($element->plaintext))
{
$county = array();
$county['id'] = $element->value;
$county['county_name'] = $element->plaintext;
$this->counties[] = $county;
}
}
}
public function getCounties()
{
return $this->counties;
}
?>
正如你可以從類見上面,我希望從我的網頁獲得縣的列表,它的所有工作作爲應該的。我想要調用的主要方法是獲得一系列縣。使用上面的代碼來獲得各縣的名單我必須做這樣的事情目前:
$scrape = new CountyScraping("http://example.com");
$scrape->setHtml();
$scrape->setCounties();
$counties = $scrape->getCounties();
這工作得很好,我可以繼續使用這個,但是我覺得我做了很多電話給getter和來自課堂外的製片人。我想我應該打一個電話,getCounties,並且在課堂上處理所有事情。
我是否正確地承擔了這個?我的getCounties()方法應該調用我的setHtml和setCounties方法嗎?或者我應該保持我的getter和setter儘可能最小並且有另一個函數呢?
任何有關我的代碼任何部分的建議都會受到歡迎。
在首位:從分析它的工作拆分取頁的工作。他們是獨立的。第二:你不需要在內部使用setter。第三:從API的角度來看,'setHtml'和'setCountries'方法看起來很奇怪。 – zerkms
你應該在'getCounties()'方法中使用getter和setter。通常最好將課堂以外的吸氣和吸氣設備的使用降到最低。相反,使用它的方法來操縱對象。 – Mark
在Yii框架中,setter和getter函數是通過繼承提供的。看看Yii,也許會適應所使用的策略。在這裏找到更多的信息:http://www.yiiframework.com/doc-2.0/guide-concept-properties.html – WeSee