A function is a piece of code that can be called many times, they can do things like calculations without the need to re-write the code a trillion times.
A class is like a group, it can hold it's own variables and functions. A class cannot just contain code, it is made to hold only functions and variables. Classes are used for the following reasons:
- They group functions and variables
- A class can have it's own properties
- It's good for organisation
- It makes the code look better easier to work with (if done correctly).
You can assign a class to a variable. You then use that variable to access the class in the script. You can make more than 1 variable assigned to the class but they are all INDEPENDENT from each over. Meaning that if you change a variable in one of the classes, it doesn't change it in the others(s).
$test1 = new Test;
$test2 = new Test;
$test1->hi = "Hello";
$test2->hi = "Bye!";
If you use $test1->hi after this, it's still "Hello" and if you use $test2->hi it's still "Bye!"
That's another reason to love classes ;)
You must assign a class to a variable before you use it or you get the following error:
Notice: Undefined variable: test in --***-- on line 2
Notice: Trying to get property of non-object in --***-- on line 2