Can I include a function inside of another function?

后端 未结 6 1159
遥遥无期
遥遥无期 2021-01-02 06:28

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:

6条回答
  •  执念已碎
    2021-01-02 06:53

    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.
    "; } else if ($roll['hAttack'] <= $roll['mDefend']) { print "Hero missed monster."; } }

提交回复
热议问题