我可能会实现您想要实现的目标,类似于此(但请记住我关于查询字符串对 POST 请求有效的评论。至少,据我所知):
abstract class HTTPRequest
{
public static function createFromGlobals()
{
$method = $_SERVER[ 'REQUEST_METHOD' ];
/* initialize additional arguments from globals */
return self::create( $method /*, additional arguments */ );
}
public static function create()
{
$arguments = func_get_args();
$method = array_shift( $arguments );
$method = ucfirst( strtolower( $method ) );
$className = __CLASS__ . $method;
if( !class_exists( $className ) )
{
throw new Exception( 'Implementation for method ' . $method . ' not found' );
}
$reflector = new ReflectionClass( $className );
return $reflector->newInstanceArgs( $arguments );
}
/* implement common functionality */
}
class HTTPRequestGet
extends HTTPRequest
{
/* implement additional GET functionality */
}
class HTTPRequestPost
extends HTTPRequest
{
/* implement additional POST functionality */
}
/* etc... */
用法:
$requestFromGlobals = HTTPRequest::createFromGlobals();
$customRequest = HTTPRequest::create( 'post', array( 'additional', 'arguments' ) );