如何在不使用die语句的情况下阻塞代码?

  • 本文关键字:情况下 代码 语句 die php
  • 更新时间 :
  • 英文 :


嗨,伙计们,我正在制作一个简单的PHP API,使用McCock架构式结构,在我的产品控制器中,我有一个创建新产品的函数,像这样

public function create()
{
$data = json_decode(file_get_contents("php://input"));
$product = $this->model('Product');
if (empty($data->name) || empty($data->co2_value)) {
http_response_code(400);
echo json_encode(
array("message" => "Bad Request")
);
die();
}
//...
}

问题是:如果我只使用echo在条件的末尾显示消息,它不会阻止代码像return语句一样运行,但是如果我使用return而不是echo,代码将不显示消息

不使用die()语句如何解决这个问题?

谢谢你的帮助

您可以简单地在echo之后添加return:

public function create()
{
$data = json_decode(file_get_contents("php://input"));
$product = $this->model('Product');
if (empty($data->name) || empty($data->co2_value)) {
http_response_code(400);
echo json_encode(
array("message" => "Bad Request")
);
return null;
}
//...
return $product;
}

基本上,如果create返回假值,则失败,否则成功。您还可以决定改为throwException,如:

public function create()
{
$data = json_decode(file_get_contents("php://input"));
$product = $this->model('Product');
if (empty($data->name) || empty($data->co2_value)) {
http_response_code(400);
throw new Exception(json_encode(
array("message" => "Bad Request")
));
}
//...
return $product;
}

相关内容

最新更新