So first im going to explain what a class and function is.
A class is a blueprint to create instances of class. So practically it is a big container full of different functions which you can use anywhere. If you make the classes in an external file (what we will be doing) then you can call the class and then functions over and over instead of having to type in the same thing 50 times.
A function is a command which can do several different things of your choosing like inserting a username and password into a database to doing calculations. Today im going to be showing you calculations and displaying text using classes and functions.
So lets get started!
The first thing we are going to do is make the class page. So lets just name it:
ourclass.php
Code: Select all
<?php
class ourclass {
}
$ourclass = new ourclass();
?>
At the bottom you see the variable called: $ourclass. What we are doing here is we are making a variable name and then setting it to the class. Then after that we declare new and then we type the name of the class which in this case is: ourclass(). If the name was hisclass then you would put new hisclass(); Also the variable name can be whatever you want, like HallsIsAmazing, as long as the word after new is the name of the class.
Then later on we can include this php file and use the $ourclass variable to call functions.
Now after this we are going to add onto it. So we are going to make a class that displays "IndieResource.com FTW". So now make the code look like this in your ourclass.php file:
ourclass.php
Code: Select all
<?php
class ourclass {
function sayThis()
{
$return = "IndieResource.com FTW";
return $return;
}
}
$ourclass = new ourclass();
?>
So what this return thing does is it takes a variable or anything that you want and sends it back to whatever called the function. So if i called this function from a different page I would put $say = $ourclass->$sayThis(); Then it will save whatever the return is to the variable $say. But I will explain it more in a second so don't worry about this right now.
Now we are going to make our main php file. We are going to call it index.php and just copy what I put into the code below..
index.php
Code: Select all
<?php
include("ourclass.php");
$say = $ourclass->sayThis();
echo $say;
?>
After that line we echo out the function $say. So what the return does in the ourclass.php is it takes the $return and send its to the variable called $say. Then we can display $say by echoing it out.
If you have done everything correctly then it should say: IndieResource.com FTW on your screen. If now then post your problems below. I will be making another tutorial on calculations later. Hope this helps!
~baseball435