Intro to Classes
Posted 10 months, 4 weeks ago at 12:59 pm. 4 comments
We’ve talked about functions before, but now we are going to talk about classes. Classes are pretty much containers for function. They can hold their own variables and functions. You write these classes to make objects. You also have a lot of control over the way the classes interact with each other.
Classes take the following format:
[code lang="c"]
Class Banker{
public $cash = 0;
public $interest = 1.06;
function __construct($balance){
$this->cash = $balance;
}
function deposit($amt){
$this->cash += $amt;
}
function withdraw($amt){
$this->cash -= $amt;
}
function giveInterest(){
$this->cash = $this->interest * $this->cash;
}
function sayBalance(){
echo $this->cash;
}
}
[/code]
Looking through that code you probably see a lot of stuff we talked about in the previous lesson about functions. However, there is also a lot of stuff I haven’t yet talked about.
The first thing I’m going to talk about are the classes variables.
[code lang="c"]
public $cash = 0;
[/code]
ignore the ‘public’ and it’s just declaring a normal variable. However, because it is in a class. It is owned by the class. This is why later in the code when you see us using $this->cash the $this will be replaced by the object because remember, the class is only a blueprint for the object.
Another thing that looks unfamiliar is the ‘__construct()’ function. What that is, is a function that runs right whean object is initiated.
[code lang="c"]
include(’bank.inc.php’);
$bankerBob = new Banker(100);
$bankerBob->giveInterest();
$bankerBob->withdraw(6);
$bankerbob->sayBalance();
[/code]
That code shows basic implementation of the class. First, we include the file the class is in. Then we declare the variable $bankerBob to be an object of the Banker class. The 100 inside the class initiation as an argument will go to the __construct() function I started talking about earlier. The account will be made with 100 dollars of what ever currency we want to imagine. The interest function adds 6 bucks to the account because 6% of 100 is 6. We then withdraw 6 bucks and bankerBob will tell us we have 100 again.
Make sense? Good.
This concludes the Introduction To Classes lesson. Comment if you are stuck with anything or have questions! Happy PHP-ing and also hope you had a Merry Christmas.
P.S. I am experimenting with different code display plug-ins. If anyone has any recommendations, say it!
Edit: I have now also found a fix to the html entity problem in wordpress thanks to this helpful site.