-1

I'm trying to add 1 to a number each time a function is called, but for some reason, the total number is always same.

Here is my current code:

 <?php
 $total;

 function draw_card() {          
     global $total;               
     $total=$total+1;            
     echo $total;
 }

 draw_card(); 
 draw_card(); 
 ?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
Desii
  • 35
  • 1
  • 8

3 Answers3

1

Personally, I would not use globals, but if I was forced at gunpoint I would handle state within the function, so outside variables did not pollute the value. I would also make an arbitrary long key name which I would not use anywhere else.

<?php
function draw_card($initial = 0) {
    $GLOBALS['draw_card_total'] = (
        isset($GLOBALS['draw_card_total']) ? $GLOBALS['draw_card_total']+1 : $initial
    );
    return $GLOBALS['draw_card_total'];        
}

// optionally set your start value
echo draw_card(1); // 1
echo draw_card();  // 2

https://3v4l.org/pinSi

But I would more likely go with a class, which holds state by default, plus its more verbose as to whats happening.

<?php
class cards {
    public $total = 0;

    public function __construct($initial = 0)
    {
        $this->total = $initial;
    }

    public function draw()
    {
        return ++$this->total;
    }

    public function getTotal()
    {
        return $this->total;
    }
}

$cards = new cards();

echo $cards->draw(); // 1

echo $cards->draw(); // 2

echo $cards->getTotal(); // 2

https://3v4l.org/lfbcL

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

Since it is global already, you can use it outside the function.

<?php


    $total;

    function draw_card() {
    global $total;
    $total=$total+1;
    //echo $total;
    }

    draw_card();
    draw_card();
    draw_card();

    echo "Current Count :", $total;

    ?>

Result : Current Count :3

This will increment the number of times you call the function. Since you echoed the result/total each time without a delimiter, you might have considered the output to be 12(Assumption)

Valerian Pereira
  • 725
  • 1
  • 6
  • 16
-1

Functions have a scope.. you just need to bring $total into the scope of the function... best to not do it globally but as an argument.

$total = 0;
function draw_card($total) {
return $total + 1;
}
$total = draw_card($total);
//Expected Output = 1
$total = draw_card($total);
//Expected Output = 2
Nicholas Koskowski
  • 793
  • 1
  • 4
  • 23
  • 2
    `global $total;` should take care of that, even if some people consider it a bad practice. Technically he isn't initializing `$total` though. – Havenard Mar 27 '18 at 17:33
  • 2
    In your example, when you call `draw_card($total)`, you are doing `draw_card(0)` both times and the expected output will be `1` for both. – Mikey Mar 27 '18 at 17:37