Defining and using a class

A class definition in PHP looks pretty much like a function declaration, but instead of using the function keyword, the class keyword is used. Let's start with a stub for our Book class:
<?php
class Book
{
    
}
?>
This is as simple as it gets, and as you can probably imagine, this class can do absolutely nothing at this point. We can still instantiate it though, which is done using the new keyword: 

$book = new Book(); 

But since the class can't do anything yet, the $book object is just as useless. Let's remedy that by adding a couple of class variables and a method:

class Nook
{
    public $title;
    public $author;
    
    public function Describe()
    {
        return "tilte : ".$this->title . " , Author: " . $this->author . " .";
    }
}
Okay, there are a couple of new concepts here. First of all, we declare two class variables, a title and an author. The variable name is prefixed by the access modifier "public", which basically means that the variable can be accessed from outside the class. We will have much more about access modifiers in one of the next part. 

Next, we define the Describe() function. As you can see, 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:
$book = new Book();
$book->title = "Cartgage";
$user->author = "hannibal";
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. $book->title is the same as saying "Give me the title variable on the $book object". After that, it's just like assigning a value to a normal variable, which we do twice, for the title and the author of the book object. In the last line, we call the Describe() method on the book object, which will return a string of information, which we then echo out. The result should look something like this: 

title:Carthage,Author:hannibal.


Post a Comment

CodeNirvana
Newer Posts Older Posts
Copyright © JEsmairi
Back To Top