0

How to increment variables ($varA $varB) in a similar style like below, or what is missing there, that this function is not working:

function myfunc($paramA,$paramB)
{
 $varA+=$paramA;
 $varB+=$paramB;
 return array($varA,$varB);
}

$increm=myfunc(2,7);
echo $increm[0]; //2
echo $increm[1]; //7

$increm=myfunc(4,5);
echo $increm[0]; //6
echo $increm[1]; //12

I want to increment variables in callback function each time this function is called.

2 Answers 2

1

There are a few different ways to do this, e.g. with global variables, but I will not encourage that. The problem is, that $varA and $varB are local to your function and will be reset (effectively to 0), each time your function is called. So, in order to keep the old values between function calls, you can try to use static class members, like this:

class myfunc {
    static private $varA = 0;
    static private $varB = 0;

    public function inc($paramA, $paramB) {
        self::$varA += $paramA;
        self::$varB += $paramB;

        return array(self::$varA, self::$varB);
    }
}

$increm = myfunc::inc(2,7);
echo $increm[0];
echo $increm[1];

$increm = myfunc::inc(4,5);
echo $increm[0];
echo $increm[1];

This will give you following output:

2
7
6
12

Alternatively you can keep your function, but still use static class members:

class MyGlobals {
    static public $varA = 0;
    static public $varB = 0;
}

function myfunc($paramA, $paramB) {
    MyGlobals::$varA += $paramA;
    MyGlobals::$varB += $paramB;

    return array(MyGlobals::$varA, MyGlobals::$varB);
}

$increm = myfunc(2,7);
$increm = myfunc(4,5);

Hope that helps

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to make callback shorter, so I could use my own method, like: something(2,7); echo$giveme[0]; echo$giveme[1]; something(4,5); echo$giveme[0]; echo$giveme[1];?
I edited my answer to reflect your request. I would not recommend using globals here, static class members seem the better choice.
0

The variables you want increment are actually in the function scope, so you can't increment then each time the function is called. Also before you need to increment sthe value of a variable you need to define its initial value.

function myfunc($varA, $varB, $paramA,$paramB)
{
 $varA += $paramA;
 $varB += $paramB;
 return array($varA,$varB);
}

You can than call your function:

$increm = myfunc(10,10,2,7);

You have than your values returned in the array.

$increm2 =myfunc($increm[0], $increm[1],2,7);

NOTE: thre are of course other ways to do that but I am trying to follow your logic which is the easiest way to go for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.