我可以在另一个函数中包含一个函数吗? [英] Can I include a function inside of another function?
本文介绍了我可以在另一个函数中包含一个函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在一个函数中包含另一个函数?为了学习功能,我试图用PHP创建一个战斗序列。顺序看起来像这样:
- 骰子会滚动,将数字分配给变量;
- Hero1攻击结果被打印;
- 骰子会滚动,将数字分配给变量;
- 将打印Hereo2攻击结果;
- 骰子会滚动,将数字分配给变量;
- 打印Hero3攻击结果。
掷骰子将是一个自动化的功能。代码如下:
<?
rollSim();
combatSim();
函数rollSim(){
$ hAttack = rand(1,20);
$ mDefend = rand(1,20);
$ mAttack = rand(1,20);
$ hDefend = rand(1,20);
$ mDamage = rand(10,25);
$ hDamage = rand(1,20);
} // end rollSim
function combatSim(){
rollSim();
if($ hAttack> $ mDefend){
print英雄命中怪物造成$ hDamage伤害。< br>;
} else if($ hAttack< = $ mDefend){
print英雄错过了怪物。;
}
} // end combatSim
?>
解决方案
您的 rollSim()
函数应返回滚动的数字,而不是设置一些变量并尝试在其他函数中使用它们。我会将它们返回到一个关联数组中,如下所示:
function rollSim(){
$ roll ['hAttack '] = rand(1,20);
$ roll ['mDefend'] = rand(1,20);
$ roll ['mAttack'] = rand(1,20);
$ roll ['hDefend'] = rand(1,20);
$ roll ['mDamage'] = rand(10,25);
$ roll ['hDamage'] = rand(1,20);
return $ roll;
function combatSim(){
$ roll = rollSim();
$ b $ if如果($ roll ['hAttack']> $ roll ['mDefend']){
print英雄打到{$ roll ['hDamage']}受到伤害。峰; br>中;
} else if($ roll ['hAttack']< = $ roll ['mDefend']){
printHero错过了怪物。
}
}
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:
- Dice would roll, assigning numbers to variables;
- Hero1 attack results are printed;
- Dice would roll, assigning numbers to variables;
- Hereo2 attack results are printed;
- Dice would roll, assigning numbers to variables;
- Hero3 attack results are printed.
The dice rolling would be an automated function. Here is the code:
<?
rollSim();
combatSim();
function rollSim() {
$hAttack = rand(1,20);
$mDefend = rand(1,20);
$mAttack = rand(1,20);
$hDefend = rand(1,20);
$mDamage = rand(10,25);
$hDamage = rand(1,20);
} // end rollSim
function combatSim() {
rollSim();
if ($hAttack>$mDefend) {
print "Hero hit monster for $hDamage damage.<br>";
} else if ($hAttack<=$mDefend) {
print "Hero missed monster.";
}
} // end combatSim
?>
解决方案
Your rollSim()
function should return the rolled numbers rather than setting some variables and trying to use them in your other function. I would return them in an associative array, like this:
function rollSim() {
$roll['hAttack'] = rand(1,20);
$roll['mDefend'] = rand(1,20);
$roll['mAttack'] = rand(1,20);
$roll['hDefend'] = rand(1,20);
$roll['mDamage'] = rand(10,25);
$roll['hDamage'] = rand(1,20);
return $roll;
}
function combatSim() {
$roll = rollSim();
if ($roll['hAttack'] > $roll['mDefend']) {
print "Hero hit monster for {$roll['hDamage']} damage.<br>";
} else if ($roll['hAttack'] <= $roll['mDefend']) {
print "Hero missed monster.";
}
}
这篇关于我可以在另一个函数中包含一个函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文