本文操作环境:windows7系统、PHP7.1、Dell G3。php方法太多参数怎么办?PHP方法参数过多优化方案我们在编写php方法时,通常有若干个参数,就像下面的代码:Class Book { public function
本文操作环境:windows7系统、PHP7.1、Dell G3。
php方法太多参数怎么办?
PHP方法参数过多优化方案
我们在编写php方法时,通常有若干个参数,就像下面的代码:
Class Book
{
public function create($name, $cateId, $author)
{
$params = [
'name' => $name,
'cateId' => $cateId,
'author' => $author
];
}
}
没有任何问题。
但是,随着业务的发展,参数可能会不断增加。就像上面的例子,创建一本书刚开始只有name/cateId/author三个参数,慢慢可能就变成了下面这样:
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!但是看起来总觉得不太优雅,当你调用这个方法的时候,鬼才知道参数的顺序是怎么样的!
如何优化呢?我们可以尝试把参数对象化。请看下面的代码:
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;
}
}
上面定义了一个BookModel类,包含了一些属性。然后我们对create方法进行改造,要求它的参数为BookModel类。由于BookModel的数据结构是明确的,使用起来非常方便。create方法调整后:
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(),
];
}
}
--结束END--
本文标题: php方法太多参数怎么办
本文链接: https://lsjlt.com/news/686.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0