wpseek.com
Outil de recherche WordPress pour les développeurs et auteurs de thèmes



clamp › WordPress Function

Depuis7.1.0
Dépréciéen/a
› clamp ( $value, $min, $max )
Paramètres: (3)
  • (mixed) $value The value to clamp.
    Requis: Oui
  • (mixed) $min The minimum bound. Must be less than or equal to `$max`.
    Requis: Oui
  • (mixed) $max The maximum bound. Must be greater than or equal to `$min`.
    Requis: Oui
Retourne:
  • (mixed) The clamped value. Either `$value`, `$min`, or `$max`.
Défini(e) dans:
Codex:

Polyfill for `clamp()` function added in PHP 8.6.

Clamps a value to be within the range of a given minimum and maximum. If the value is within the bounds, the original value is returned. If it is not within the bounds, the closest bound is returned.


Fonctions en relation: clean_pre

Source

function clamp( $value, $min, $max ) {
		$throw_value_error = static function ( string $message ) {
			// The ValueError class was introduced in PHP 8, so in 7.4 throw InvalidArgumentException instead.
			if ( ! class_exists( 'ValueError', false ) ) {
				throw new InvalidArgumentException( $message );
			}
			throw new ValueError( $message );
		};

		if ( is_float( $min ) && is_nan( $min ) ) {
			$throw_value_error( 'clamp(): Argument #2 ($min) must not be NAN' );
		}

		if ( is_float( $max ) && is_nan( $max ) ) {
			$throw_value_error( 'clamp(): Argument #3 ($max) must not be NAN' );
		}

		if ( $max < $min ) {
			$throw_value_error( 'clamp(): Argument #2 ($min) must be smaller than or equal to argument #3 ($max)' );
		}

		/*
		 * The upper bound is checked before the lower bound to match the order in PHP's
		 * implementation. Comparison in PHP is not transitive when operands of different
		 * types are mixed (for example, comparing against a bool coerces both operands to
		 * bool), so both bounds can compare as exceeded at once, and the first check wins.
		 */
		if ( $value > $max ) {
			return $max;
		}

		if ( $value < $min ) {
			return $min;
		}

		return $value;
	}
}