ArgumentCount
云策文档标注
概述
ArgumentCount 是 WordPress 中的一个异常类,用于处理向方法传递参数数量不正确的情况。它通常用于方法参数可选但需成组传递的场景,或当方法期望特定元素数量的数组时。
关键要点
- ArgumentCount 继承自 Exception,专门用于参数数量错误的异常处理。
- 主要应用场景:方法参数全可选但需成组传递(如无参数或两个参数,但不能一个参数),或方法期望特定元素数量的数组。
- 提供静态方法 ArgumentCount::create() 来创建标准化的异常消息。
代码示例
final class ArgumentCount extends Exception {
public static function create($expected, $received, $type) {
$stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
return new self(
sprintf(
'%s::%s() expects %s, %d given',
$stack[1]['class'],
$stack[1]['function'],
$expected,
$received
),
$type
);
}
}
原文内容
Exception for when an incorrect number of arguments are passed to a method.
Description
Typically, this exception is used when all arguments for a method are optional, but certain arguments need to be passed together, i.e. a method which can be called with no arguments or with two arguments, but not with one argument.
Along the same lines, this exception is also used if a method expects an array with a certain number of elements and the provided number of elements does not comply.
Methods
| Name | Description |
|---|---|
| ArgumentCount::create | Create a new argument count exception with a standardized text. |
Source
final class ArgumentCount extends Exception {
/**
* Create a new argument count exception with a standardized text.
*
* @param string $expected The argument count expected as a phrase.
* For example: `at least 2 arguments` or `exactly 1 argument`.
* @param int $received The actual argument count received.
* @param string $type Exception type.
*
* @return WpOrgRequestsExceptionArgumentCount
*/
public static function create($expected, $received, $type) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
$stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
return new self(
sprintf(
'%s::%s() expects %s, %d given',
$stack[1]['class'],
$stack[1]['function'],
$expected,
$received
),
$type
);
}
}
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |