Okay guys.
So pure functions.
That's an example of a pure function.
When you run a pure function with the same arguments, you always get the same result.
So the first round, second round it is exactly the same.
Now an example of a non pure function.
So this one has some dependency on a shared state and has side effect.
So it modifies the global state.
When this run for the first time the result is five.
When it's run for the second time the result is ten.
Even though you supply the same arguments, that's because it has side effects and it is dependent on
the shared state.
So let's actually write this code.
Let's create a pure PHP file, open it right away.
Are the PHP tag and implement this add function, which is pure.
It has two arguments.
We can also type them as.
Why not?
So those are integers.
The return type is also an integer and we return a plus b.
Like that.
Now if I echo or vardump the result of calling this function, I should get the same result every single
time.
So I'm calling add with those two parameters.
Maybe let's do that again and just var dump this immediately.
I need to jump to functions folder and run pure PHP.
Now as you see we've got two exactly the same results.
Now let's do the second example from the slide.
So define the function called add to total that just accepts a value.
But this one.
This is using a global variable that I'm going to define right here.
And to use this variable I need to use the global keyword.
And now I have access to the original total variable from outside this function.
So if I add something to total.
And I return it then as you've seen on the slide, this actually is influencing some outside state,
some variables that are outside this function.
And this is called a side effect.
So if you are calling a function and you would like to actually calculate something, but instead a
global state is modified which you might be aware of or you might not be.
Then this function is not considered pure.
Now let's run that.
So I'm going to var dump two calls to this function with the same parameters.
So this is maybe.
Sorry that's just one parameter.
Let's maybe call with three and another call with the same one.
So we can see the different output.
So we are calling pure PHP.
The first call returns three.
The second call returns six.
Okay so what's the point.
Well the pure functions they are predictable.
You always know that you're going to get the same output for the same input.
It's easier to test such functions and they are easily reusable.
Also the result of such functions can be cached.