在 php 中使用抽象 类 来获取和 post HTTPData 并演示它是如何工作的

Using abstract classes in php to get and post HTTPData and demonstrate how it works

我目前正在学习 PHP 编程的基础知识,但我无法理解抽象的 classes。我有一个包含 3 个 class 的程序,不包括一个 index.php 来证明它有效,这将证明一个抽象 class 被另外两个继承。第一个class 调用的HTTPData 是一个抽象class,只有一个抽象方法,即getKey($key)。另外两个 classes,称为 HTTPGetData 和 HTTPPostData,扩展了 HTTPData class 并且都具有相同的 getKey($key) 方法,只是不抽象。我不能硬编码 $key 的内容,所以我不能硬编码 $_GET["name"] 让它正常工作,我也不能在任何 classes 中回显任何一个。尽管如此,我知道 $_GET 和 $_POST 是用于捕获 HTTP 用户数据的超级全局变量,可以通过传递 $_GET["username"] 这样的键来访问。我觉得应该返回什么.我想我的问题是..我该怎么做而不回显任何语句,你将如何实现它?

这是我到目前为止的代码: HTTPData.php:

<?php

abstract class HTTPData {

   abstract public function getKey($key);
}
?>

HTTPGetData.php:

<?php

class HTTPGetData extends HTTPData {

public function __construct() {

}

public function getKey() {
   return $this->key;
  }
 }
?>

HTTPPostData:

<?php

class HTTPPostData extends HTTPData{

public function __construct() {

}

public function getKey() {
   return $this->key;
  }


}
?>

index.php:

<?php


 if( isset($_GET['key'])) {
 /*How would I not echo this?*/
}


?>

我知道这并不多,但我在 PHP 中很难理解这一点...如果有任何帮助,我们将不胜感激。我的书只是没有教 $_GET 和 $_POST 抽象到我可以处理这样的问题的地方。谢谢你的时间,如果这是一个简单的问题,如果不知道答案是愚蠢的...

,我深表歉意

您可以提取 $_GET$_POST 作为依赖项,以便能够在服务器上下文之外测试您的 classes:

abstract class HTTPData
{
    private $data;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function getKey($key)
    {
        return $this->data[$key] ?? null;
    }
}

然后你的具体 classes 将继承这个抽象 class:

final class HTTPGetData extends HTTPData
{

}

final class HTTPPostData extends HTTPData
{

}

最后,您可以自己测试 classes,提供 $_GET$_POST

$_GET = ['foo' => 'bar'];
$_POST = ['baz' => 'quux'];

$httpGetData = new HTTPGetData($_GET);
$httpPostData = new HTTPPostData($_POST);

assert($httpGetData->getKey('foo') === 'bar');
assert($httpGetData->getKey('baz') === null);

assert($httpPostData->getKey('baz') === 'quux');
assert($httpPostData->getKey('foo') === null);

这里是the demo.

理智的问题是:但为什么我需要两个 classes,它们共享相同的功能,只是名称不同? 为了回答这个问题,我们必须看dependency injection (DI). With such tool as DI, you can resolve dependencies automatically (well almost). So, when your other class will need an object of either HTTPGetData or HTTPGetData (can be type hinted的概念或配置),DI容器将用正确的params数组实例化正确的class并传递它。