The community is working on translating this tutorial into Arabic, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".
Defining and using a class
After the introduction to classes in the previous chapter, we're now ready to write our very own class. It will hold information about a generic user, for instance a user of your website.
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 User class:
<?php
class User
{
}
?>
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:
$user = new User();
But since the class can't do anything yet, the $user object is just as useless. Let's remedy that by adding a couple of class variables and a method:
class User
{
public $name;
public $age;
public function Describe()
{
return $this->name . " is " . $this->age . " years old";
}
}
Okay, there are a couple of new concepts here. First of all, we declare two class variables, a name and an age. The variables name and age are prefixed by the access modifier "public", which basically means that the variables can be accessed from outside the class. We will have much more about access modifiers in one of the next chapters.
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:
$user = new User();
$user->name = "John Doe";
$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's 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:
John Doe is 42 years old
Congratulations, you have just defined and used your first class, but there is much more to classes than this. In the following chapters, we will have a look at all the possibilities of PHP classes.