Programming With OOPS

In this article we will learn Programming with OOPS, it will show you that how to create objects, define their attributes (as properties) and methods. Objects in php are always created using a “class” keyword. In this article, “Programming with OOPS”, we will also learn the details of classes, properties and methods. As a full of this article, this is good resource to learn OOPS.

As I said above, you can create and object in PHP using the “class” keyword. A class consists of some properties and methods, either public or private. Here I provided the very example that is following and I will explain it better.

In the previous code, we have started with “class Emailer”, which means that the name of our class is Emailer. While naming a class, follow the same naming convention as variables. For example, you can’t start class name with numeric letter.

After that we have declared the properties of this class. There are four properties here, namely, $sender, $recipient, $subject,  and  $body. It is notable that we have declared all this properties with private keyword. A private property means that this property can only be accessed internally from this class. Properties are nothing but variables inside a class.

In this class there are five functions,  __construct(), addRecipient(), setSubject(), setBody(), and sendEmail(). It is notable that last four methods are declared public. That means when someone instantiate this object then they can access these methods. The __construct() is a special method inside a class which is called constructor method. When a new object is created from this class then this method is called automatically. So if we want to perform any preliminary task then we can do in the construct method. In the previous example we just set the $recipient  as a blank array and we also set the sender name.

Accessing properties and methods from inside the class

Here you will see that how can we access the method and properties inside the class.

In the previous code there is a private property named $body inside our class, if we want to access it from within the function, we must refer to it with $this. $this means a reference to current instance of this object. So we can access the body property with $this->body.  Please note that we have to access the properties of a class using a “->” following the instance. Similarly, like properties, we can access any member method from inside another member method in this format. For example, we can evoke setSubject  method as  $this->setSubject().

Using an object

We must note some things before using and object. You must initiate an object before using it. After initiating, you can access all its public properties and methods using “->” after the instance. For example:

In the above code piece, we first created an instance of Emailer class to variable name $emailerobject in the first line.