php函数参数过多_PHP方法参数过多优化方案

22aaab3c59086da1a0585f8fd91c17e1.png

我们在编写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(),

];

}

}

看,面向对象编程的优势在这里凸显出来了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值