Define and Use a Constant
Defines a PHP constant only when it is not already defined, then uses it in a small configuration calculation.
Purpose
Defines a PHP constant only when it is not already defined, then uses it in a small configuration calculation.
Snippet details
ContextUtilityLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Define and Use a Constant.
*
* Purpose:
* Shows how to define a constant once, check for it with defined(), and use it
* as a stable application setting.
*
* @param int $active_ships Number of active ships currently shown.
* @return array Constant value and capacity status.
*/
function ogSnippetDefineAndUseAConstant(int $active_ships): array {
if (defined('OG_SNIPPET_FLEET_LIMIT') === false) {
define('OG_SNIPPET_FLEET_LIMIT', 12);
}
if ($active_ships < 0) {
return array(
'success' => false,
'fleet_limit' => OG_SNIPPET_FLEET_LIMIT,
'message' => 'Active ship count cannot be negative.'
);
}
$slots_remaining = OG_SNIPPET_FLEET_LIMIT - $active_ships;
if ($slots_remaining < 0) {
$slots_remaining = 0;
}
return array(
'success' => true,
'fleet_limit' => OG_SNIPPET_FLEET_LIMIT,
'active_ships' => $active_ships,
'slots_remaining' => $slots_remaining,
'at_capacity' => $active_ships >= OG_SNIPPET_FLEET_LIMIT
);
}
/*
$result = ogSnippetDefineAndUseAConstant(9);
print_r($result);
*/