php response响应,9. 响应 (Response)
## 為什么單獨創建一個Response?
跟`為什么要單獨創建一個Request` 一樣。
原因: 可以管理
如: 在 `swoole` 不應該用 `echo`, 因為 `swoole` 是 `cli` 運行,只會輸出在命令行。
`必須` 只有一個地方能 `輸出響應` 就是此篇的功能
確保有 `集中控制權` 是非常重要 !
(后面代碼有 `echo` 都是不規范的, 應該調用 `此篇` 的功能)
## 創建core/Response.php
```
namespace core;
class Response
{
protected $headers = []; // 要發送的請求頭
protected $content = ''; // 要發送的內容
protected $code = 200; // 發送狀態碼
public function sendContent() // 發送內容
{
echo $this->content;
}
public function sendHeaders() // 發送請求頭
{
foreach ($this->headers as $key => $header)
header($key.': '.$header);
}
public function send() // 發送
{
$this->sendHeaders();
$this->sendContent();
return $this;
}
public function setContent($content) // 設置內容
{
if( is_array($content))
$content = json_encode($content);
$this->content = $content;
return $this;
}
public function getContent() // 獲取內容
{
return $this->content;
}
public function getStatusCode() // 獲取狀態碼
{
return $this->code;
}
public function setCode(int $code) // 設置狀態碼
{
$this->code = $code;
return $this;
}
}
```
## 在容器綁定Response類
編輯 `app.php`的`register` 方法

## 編輯index.php


總結
以上是生活随笔為你收集整理的php response响应,9. 响应 (Response)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多任务场景下单线程异步多线程多进程
- 下一篇: eclipse java ui,Ecli