新聞中心
本文操作環(huán)境:Windows7系統(tǒng)、php7.1、Dell G3。

創(chuàng)新互聯(lián)為您提適合企業(yè)的網(wǎng)站設(shè)計(jì)?讓您的網(wǎng)站在搜索引擎具有高度排名,讓您的網(wǎng)站具備超強(qiáng)的網(wǎng)絡(luò)競(jìng)爭(zhēng)力!結(jié)合企業(yè)自身,進(jìn)行網(wǎng)站設(shè)計(jì)及把握,最后結(jié)合企業(yè)文化和具體宗旨等,才能創(chuàng)作出一份性化解決方案。從網(wǎng)站策劃到成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè), 我們的網(wǎng)頁(yè)設(shè)計(jì)師為您提供的解決方案。
php方法太多參數(shù)怎么辦?
PHP方法參數(shù)過(guò)多優(yōu)化方案
我們?cè)诰帉?xiě)PHP方法時(shí),通常有若干個(gè)參數(shù),就像下面的代碼:
Class Book
{
public function create($name, $cateId, $author)
{
$params = [
'name' => $name,
'cateId' => $cateId,
'author' => $author
];
}
}沒(méi)有任何問(wèn)題。
但是,隨著業(yè)務(wù)的發(fā)展,參數(shù)可能會(huì)不斷增加。就像上面的例子,創(chuàng)建一本書(shū)剛開(kāi)始只有name/cateId/author三個(gè)參數(shù),慢慢可能就變成了下面這樣:
Class Book
{
public function create($name, $cateId, $author, $year, $price, $publish, $country, $language)
{
$params = [
'name' => $name,
'cateId' => $cateId,
'author' => $author,
'year' => $year,
'price' => $price,
'publish' => $publish,
'country' => $country,
'language' => $language,
];
}
}It works well!但是看起來(lái)總覺(jué)得不太優(yōu)雅,當(dāng)你調(diào)用這個(gè)方法的時(shí)候,鬼才知道參數(shù)的順序是怎么樣的!
如何優(yōu)化呢?我們可以嘗試把參數(shù)對(duì)象化。請(qǐng)看下面的代碼:
class BookModel
{
protected $name;
protected $cateId;
protected $author;
protected $year;
protected $price;
protected $publish;
protected $country;
protected $language;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getCateId()
{
return $this->cateId;
}
public function setCateId($cateId)
{
$this->cateId = $cateId;
}
public function getAuthor()
{
return $this->author;
}
public function setAuthor($author)
{
$this->author = $author;
}
public function getYear()
{
return $this->year;
}
public function setYear($year)
{
$this->year = $year;
}
public function getPrice()
{
return $this->price;
}
public function setPrice($price)
{
$this->price = $price;
}
public function getPublish()
{
return $this->publish;
}
public function setPublish($publish)
{
$this->publish = $publish;
}
public function getCountry()
{
return $this->country;
}
public function getLanguage()
{
return $this->language;
}
public function setLanguage($language)
{
$this->language = $language;
}
}上面定義了一個(gè)BookModel類,包含了一些屬性。然后我們對(duì)create方法進(jìn)行改造,要求它的參數(shù)為BookModel類。由于BookModel的數(shù)據(jù)結(jié)構(gòu)是明確的,使用起來(lái)非常方便。create方法調(diào)整后:
Class Book
{
public function create(BookModel $bookModel)
{
$params = [
'name' => $bookModel->getName(),
'cateId' => $bookModel->getCateId(),
'author' => $bookModel->getAuthor(),
'year' => $bookModel->getYear(),
'price' => $bookModel->getPrice(),
'publish' => $bookModel->getPublish(),
'country' => $bookModel->getCountry(),
'language' => $bookModel->getLanguage(),
];
}
}看,面向?qū)ο缶幊痰膬?yōu)勢(shì)在這里凸顯出來(lái)了!
當(dāng)前標(biāo)題:php方法太多參數(shù)怎么辦
文章地址:http://fisionsoft.com.cn/article/dpisgoo.html


咨詢
建站咨詢
