【发布时间】:2017-10-07 11:32:15
【问题描述】:
让我们假设这个类:
<?php
namespace app;
class SimpleClass {
protected $url = '';
protected $method = 'GET';
public function __construct( $url, $method = 'GET' )
{
$this->url = $url;
$this->method = $method;
}
public function get()
{
$this->prepare_something();
// other things...
}
public function post()
{
$this->prepare_something();
// other things...
}
public function patch()
{
$this->prepare_something();
// other things...
}
public function put()
{
// other things...
}
public function delete()
{
// other things...
}
protected function prepare_something()
{
// preparing...
}
正如你在这个类的三个方法中看到的; get, post, patch 我们使用 preparing_something 方法,但在 put, delete 方法中我们不使用。
我不得不重复 3 次 $this->prepare_something();。这3种方法中的一次get, post, patch。在这 3 个方法的开头是 3 lines 相同的调用。
但假设我们有 100 种方法。
在其中 70 个中我们使用 $this->prepare_something();,而在 30 个中我们没有。
这70种方法中有没有办法auto-call这些方法?无需编写这 70 种方法中的每一种$this->prepare_something();?
这只是痛苦,在某些方法中必须一直调用相同的方法$this->prepare_something(); 感觉不对...
【问题讨论】: