本文操作环境: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(), ]; } }
看,面向对象编程的优势在这里凸显出来了!
名称栏目:php方法太多参数怎么办
路径分享:http://www.mswzjz.cn/qtweb/news43/299893.html
攀枝花网站建设、攀枝花网站运维推广公司-贝锐智能,是专注品牌与效果的网络营销公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 贝锐智能