cant increment PHP class's static variable

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

  1. narekm

    narekm New Member

    Joined:
    Mar 23, 2011
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    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

    Joined:
    Mar 23, 2011
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    Please just delete "echo"-s in front of change functions .. even in that case it didnt work
     
  3. pein87

    pein87 Active Member

    Joined:
    Aug 6, 2010
    Messages:
    173
    Likes Received:
    47
    Trophy Points:
    28
    Occupation:
    Web Dev
    Location:
    Limbo
    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

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice