Page 184 - Open Soource Technologies 304.indd
P. 184
Web Technologies-I
Notes Okay, there are a couple of new concepts here. First of all, we declare two class variables, a
name and an age. The variable name is prefixed by the access modifier “public”, which basically
means that the variable can be accessed from outside the class.
Next, we define the Describe () function. It looks just like a regular function declaration, but with
a couple of exceptions. It has the public keyword in front of it, to specify the access modifier.
Inside the function, we use the “$this” variable, to access the variables of the class it self. $this
is a special variable in PHP, which is available within class functions and always refers to the
object from which it is used.
Now, let’s try using our new class. The following code should go after the class has been
declared or included:
$user = new User ();
$user->name = “Piyush”;
$user->age = 42;
echo $user->Describe();
The first thing you should notice is the use of the -> operator. We used it in the Describe ()
method as well, and it simply denotes that we wish to access something from the object used
before the operator. $user->name is the same as saying “Give me the name variable on the $user
object”. After that, it is just like assigning a value to a normal variable, which we do twice, for
the name and the age of the user object. In the last line, we call the Describe () method on the
user object, which will return a string of information, which we then echo out. The result should
look something like this:
Piyush is 42 years old
8.5.1 Constructors and Destructors
Constructors
Constructor and destructor are special functions which are automatically called when an object
is created and destroyed. The constructor is the most useful of the two, especially because it
allows you to send parameters along when creating a new object, which can then be used to
initialize variables on the object. Here’s an example of a class with a simple constructor:
class Animal
{
public $name = “No-name animal”;
public function __construct()
{
echo “I’m alive!”;
}
}
As you can see, the constructor looks just like a regular function, except for the fact that it
starts with two underscores. In PHP, function with two underscore characters before the name
usually tells you that it is a so-called magic function, a function with a specific purpose and
extra functionality, in comparison to normal functions. So, a function with the exact name
“__construct”, is the constructor function of the class and will be called automatically when the
object is created. Let’s try doing just that:
178 LOVELY PROFESSIONAL UNIVERSITY