Functions in PHP are a lot like functions in math class. They take some input, do something, and then return some output.
Throughout this course we’ve been using the print function. This is a function PHP provides for us. There are whole bunch of these pre-made functions you can use for all sorts of things, more than a thousand, but you can also write your own functions.
Functions are there to make your life easier. Whenever you find yourself repeating a piece of code, use a function. That way, there's a single place to make changes. Take this for example:(gesture)
Functions are important for organizing code as well. It can get very difficult very quickly if you have all of your code in one long block. Functions allow us to group things logically, and make code easier to understand.
Let's make one.
We start with the word function, then the name, my_function, empty parentheses, and some braces.
We make the function give us back a value, using the return statement:(gesture)
This function is not very interesting. Let's add some arguments. Arguments are variables that get added when you call a function.
This function accepts two arguments, A and B. It then adds them together, and returns the value.
Our function can now be re-used to add any 2 numbers. woohoo
What if we tried to access the variable C, from outside the function, like: (gesture)
$value = my_function(1, 2); print $c;
This will cause an error.
That’s because the variable c isn’t available from outside the function. This is known as variable scope. Any variables created inside the function are only available from within in it.
There is a way around this. Using the global keyword, you can declare that a variable is available from anywhere.
So, we could make c available like this:
Global variables should be avoided whenever possible. While having a variable available from anywhere seems handy, they make it very difficult to figure out who modified the variable. This leads to problems when debugging, and debugging is something you will be doing a lot of.
You just went all the way with PHP. How does it feel?
If you want some more action, check out our other videos.
Questions or Comments?