Created
February 20, 2023 06:13
-
-
Save crazywhalecc/359cce4b666b74ea27eb3a50da3bfd88 to your computer and use it in GitHub Desktop.
ActionResponse.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ActionResponse implements \JsonSerializable, \IteratorAggregate | |
{ | |
public string $status = 'ok'; | |
public int $retcode = 0; | |
/** | |
* @var mixed | |
*/ | |
public $data = []; | |
public string $message = ''; | |
/** | |
* @var mixed | |
*/ | |
public $echo = null; | |
public static function create($echo = null): ActionResponse | |
{ | |
$a = new self(); | |
if ($echo !== null) { | |
$a->echo = $echo->echo; | |
} | |
return $a; | |
} | |
public function ok($data = []): ActionResponse | |
{ | |
$this->status = 'ok'; | |
$this->retcode = 0; | |
$this->data = $data; | |
$this->message = ''; | |
return $this; | |
} | |
/** | |
*/ | |
#[\ReturnTypeWillChange] | |
public function getIterator(): \ArrayIterator | |
{ | |
return new \ArrayIterator($this->jsonSerialize()); | |
} | |
public function jsonSerialize(): array | |
{ | |
$data = []; | |
foreach ($this as $k => $v) { | |
echo "循环到 $k => $v\n"; | |
if ($k === 'echo' && $v === null) { | |
continue; | |
} | |
$data[$k] = $v; | |
} | |
return $data; | |
} | |
} | |
$res = ActionResponse::create()->ok(); | |
var_dump($res->getIterator()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment