In case you haven't been reading, here is the series so far:
Last time, I introduced the concepts of classes and objects. To recap, a class is a template and an object is the product of that template. Next on the list are properties, constructors and methods.
Let's start with the class MyFirstClass from part 1 and add some properties.
class MyFirstClass {
public $classLoc;
protected $buildingNum;
private $teacher;
}
Here we have added three properties or data members. The three properties have the access modifies public, protected and private, however we will address that significance later. Properties initialized outside of methods are global in scope, unless the access modifier overrides that, again, we'll look at that later. Properties initialized within a method is local to the method. Furthermore, you can usually set and get the value for properties outside of the class, notice we don't use the dollar sign ($) for the variable:
MyFirstClass->classLoc = "Building B";
A method is basically a function within a class. In fact, they are usually initialized with the keyword function.
class MyFirstClass {
public $classLoc;
protected $buildingNum;
private $teacher;
function FirstMethod() {
// method code
}
}
Just like data members, methods can have public, protected and private access modifiers and is implicitly public if no access modifier is assigned. A method is accessed via it's class, so in the preceding example, we would access it as such:
print MyFirstClass->FirstMethod();
Here we invoke the method FirstMethod from inside the class MyFirstClass.
In PHP 5, there is the concept of a constructor. This is the function or method that is run when a new instance of a class is made. The constructor method requires the __construct() keyword, which happens to be what is called a 'magic method'.
class MyFirstClass {
public $classLoc;
protected $buildingNum;
private $teacher;
function __construct() {
// this is invoked at the initialization of a new object
}
function FirstMethod() {
// method code
}
}
Finally, to create a new instance of a class you create a variable and use the new keyword along with the class name:
$instance = new MyFirstClass();
So there you have it. We have covered the basic concepts of classes and objects and looked at properties, methods and constructors. Next we will look a objects a little more.