Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Auto increment an int $order variable within a class based on how many instances of that class have been instantiated

This may seem like an odd question. I do have some answers and I’m overall thinking this isn’t possible, but then I remember reading something about a type of variable that persists throughout an apps life. I’m not really sure how to word it so here is some PHP code that hopefully should communicate what I’m trying to do:

class Step
{

    // This is the variable I want to auto increment somehow
    public int $stepOrder = 1;

}


$steps = [
    new Step(),
    new Step(),
    new Step(),
];


echo $steps[0]->stepOrder; // int 1
echo $steps[1]->stepOrder; // int 2
echo $steps[2]->stepOrder; // int 3

Hopefully you get the idea. Is this possible without using session or manually setting the order when instantiating?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a class static property that you increment in the constructor.

class Step
{
    static int $currentStepOrder = 1;

    public __construct() {
        $this->stepOrder = self::$currentStepOrder++;
         //...
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading