每次编写一些php函数或类方法时,最好检查输入参数并抛出异常,或触发错误或警告等...
例如
<?php
function send_email($email, $subject, $body)
{
if (empty($email)) {
throw new InvalidArgumentException('Email should not be empty');
}
if (!is_string($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new InvalidArgumentException('Email format is invalid');
}
if (empty($subject)) {
throw new InvalidArgumentException('Subject should not be empty');
}
if (!is_string($subject)) {
throw new InvalidArgumentException('Subject must be a string');
}
if (empty($body)) {
throw new InvalidArgumentException('Body should not be empty');
}
if (!is_string($body)) {
throw new InvalidArgumentException('Body must be a string');
}
return mail($email, …Run Code Online (Sandbox Code Playgroud)