Can I include a function inside another function?
The short answer is yes, but how you do it depends entirely on your goal. In your specific combat simulation example, you are asking if one function can call another. That is standard behavior in PHP and works exactly as written. You defined rollSim() to generate random values and stored them in variables like $hAttack and $mDefend. Then, inside combatSim(), you invoked rollSim() to populate those variables before checking the logic. This creates a clear separation of concerns: one function handles data generation, while the other handles the game state evaluation.
However, there is a subtle distinction between including (calling) and nesting. If your intent was to define rollSim inside the scope of combatSim, PHP would throw a fatal error. Functions are top-level constructs in PHP; you cannot declare a function within another function's body. Attempting to write:
function combatSim() {
function rollSim() { // This will cause a Fatal Error
$hAttack = rand(1, 20);
}
}
is invalid syntax. The language parser expects a block of statements after the opening brace of combatSim, not another function declaration. If you need that logic to be available only when combatSim runs, calling the top-level function is the correct approach.
Handling Variable Scope and State
Looking closely at your code, there is a significant architectural pitfall regarding variable scope. In rollSim(), you assign values to variables like $hAttack. These are local to that function. When combatSim() calls rollSim(), those variables come into existence within the scope of rollSim. Once rollSim finishes executing, those specific variables cease to exist in their own context.
If combatSim relies on $hAttack being available after calling rollSim(), you are relying on the function returning or having a global side effect. In your current snippet, there is no return statement inside rollSim. While PHP allows functions to execute without returning values, relying on global state or implicit return of void when variables are needed creates fragility. If you ever add logic to combatSim that calls itself recursively or interacts with other systems, those internal variables will vanish unless they are explicitly returned and captured.
To make this robust, rollSim should return an associative array containing the roll results:
function rollSim() {
return [
'hAttack' => rand(1, 20),
'mDefend' => rand(1, 20),
'mAttack' => rand(1, 20),
'hDefend' => rand(1, 20),
'mDamage' => rand(10, 25),
'hDamage' => rand(1, 20)
];
}
function combatSim() {
$stats = rollSim(); // Capture the data
if ($stats['hAttack'] > $stats['mDefend']) {
print "Hero hit monster for {$stats['hDamage']} damage.<br>";
} else {
print "Hero missed monster.";
}
}
This approach decouples the generation logic from the logic that consumes it. It ensures that even if rollSim is called multiple times or by different parts of your application, the data remains encapsulated and safe to use.
Refactoring for Reusability
As your combat sequence growsâadding Hero 2, Hero 3, and more complex dice mechanicsâthe linear repetition of variable names becomes unmanageable. The current structure forces you to duplicate logic for every new hero or monster interaction. A better pattern is to pass the roll results as arguments to a generic attack resolution function.
function resolveAttack($attackerName, $defenderName, $attackVal, $defendVal, $damage) {
if ($attackVal > $defendVal) {
return "{$attackerName} hit {$defenderName} for {$damage} damage.";
}
return "{$attackerName} missed {$defenderName}.";
}
function combatSim() {
$rolls = rollSim();
// Hero 1 vs Monster
echo resolveAttack('Hero', 'Monster', $rolls['hAttack'], $rolls['mDefend'], $rolls['hDamage']);
// You can easily extend this pattern for subsequent turns
}
This shift allows you to handle the sequence steps (dice rolling, printing results) cleanly without nesting logic or duplicating variable declarations. It adheres to the principle of composing small, testable functions rather than building monolithic blocks where internal state is hard to track.
If you are looking for a framework that simplifies these kinds of object-oriented structures and service management, Laravel provides robust tools for organizing complex game logic into controllers or service classes. You might find the architecture patterns discussed at https://laravelcompany.com helpful for scaling this type of simulation beyond simple procedural scripts.