1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

cant increment PHP class's static variable

Discussion in 'PHP' started by narekm, Aug 1, 2011.

  1. narekm

    narekm New Member

    Hello there. Here is my php code
    PHP:
    class car{
    static 
    $one=1;

    static function 
    change()
    {
     
    self::$one=self::$one++;

    }

    }
    car::$one=2;
    echo 
    car::$one."<br />";
    echo 
    car::change();
    echo 
    car::$one."<br />";
    echo 
    car::change();
    echo 
    car::$one."<br />";
    echo 
    car::change();
    echo 
    car::$one."<br />";



    I expected it to increment the variable but it echoed 2 2 2 2 instead of expected 2 3 4 5

    Thank you for your attention!!!

    Will be waiting :pleased:
     
  2. narekm

    narekm New Member

    Please just delete "echo"-s in front of change functions .. even in that case it didnt work
     
  3. pein87

    pein87 New Member

    try

    PHP:
    class car

    static 
    $one=1

    static function 
    change() 

     return 
    self::$one++; 



    }

    $i;
    for (
    $i 1$i 11$i++)
    {
    echo 
    car::change();
    }
    the for loop just makes it print out a certain number of times, while the change function changes the value on each call.

    if you use the below script it will show the value as 10
    PHP:
    <?php

    class car

    static 
    $one=1

    static function 
    change() 

     return 
    self::$one++; 



    }

    car::change();
    car::change();
    car::change();
    car::change();
    car::change();
    car::change();
    car::change();
    car::change();
    car::change();
    echo 
    car::$one;

    ?>
    Hope this works, I did test the code and it worked on my machine using php 5.2.11. and 5.3.5
     
    Last edited: Aug 3, 2011

Share This Page