Is it possible to include one function inside another? To learn functions, I\'m trying to create a combat sequence using PHP. The sequence would look like this:
No, you can't really do what you're asking. Even if you embedded the declaration of rollSim()
inside the definition of combatSim()
(which you can do, that's legal but has no real effects), the variables you're setting in rollSim()
would still be local to it and inaccessible by combatSim()
.
You need a better way of passing around the information you're concerned with. Jeremy Ruten details a good way. Another way would be to define an object that's responsible for modeling your combat event and have rollSim()
and combatSim()
both be methods on it.
class myCombat {
private $hAttack;
private $mDefend;
private $mAttack;
private $hDefend;
private $mDamage;
private $hDamage;
function rollSim() {
$this->hAttack = rand(1, 20);
$this->mDefend = rand(1, 20);
$this->mAttack = rand(1, 20);
$this->hDefend = rand(1, 20);
$this->mDamage = rand(10, 25);
$this->hDamage = rand(1, 20);
}
function combatSim() {
$this->rollSim();
if($this->hAttack > $this->mDefend)
echo 'Hero hit monster for ' . $this->hDamage . ' damage.
';
else
echo 'Hero missed monster';
}
}
$combat = new myCombat;
$combat->combatSim();