Object-oriented programming (OOP) was integrated into the PHP version 3 in 1998, including basic class and object support. In 2000, PHP4 added some functionality, but suffered from its non-intuitive handling of references with objects handled like value types.
Finally, in 2004, PHP5 included an extensive rewrite of object handling with the introduction of Zend Engine 2, featuring a comprehensive feature set and increased performance.
But at that time, the PHP object model was far too brief. We could really talk about object oriented programming. PHP Developers are then examined the issue and improved the object model that, since version 5, has nothing to envy to other objects languages like Java or C++.
This first course on object-oriented programming will be a first discovery and presentation of class writing syntax. We will address initially the benefits relating to a subject approach. Then we will define the concepts of classes, objects, and instance type before we fully in the writing of our first classes.
We’ll be covering the following topics in this tutorial:
What are the advantages and disadvantages of an object approach?
OOP offers many advantages. Among them :
• The ability to reuse code in different projects. The classes thus created will have a new life in a third party application.
• A design of the algorithm more clear and organized. The programmer identifies each element of the program as an object with its context, its properties and actions of its own.
• A modular code. Each object type has its own context and can act with others according to the specific interfaces. This isolates each module and create new ones that will be added separately to the application. This approach is particularly used in the case of projects distributed between many developers.
• Ability to adapt to the design patterns (design patterns) for better structuring the code.
However, there are some drawbacks to the use of object-oriented programming:
• A poorly conceptualized object oriented application will be difficult to maintain and modular.
• Object-oriented programming generally requires more resources and execution times that a procedural code.
Note: object-oriented programming is not synonymous with good programming. There are excellent developers capable of producing good procedural code, maintainable, modular and structured. But there are also developers programming object that produce bad code due to a lack of conceptualization.
What is an object?
Definition
An “object” is a representation of a material or immaterial thing real that is associated properties and shares.
For example: a car, a person, an animal, a number or a bank account can be seen as objects.
Attributes
The “attributes” (also called “data members”) are the specific characteristics of an object.
A person, for example, have different attributes of its own as the name, first name, eye color, gender, hair color, size …
Methods
The “methods” are the actions for an object.
A person object, for example, provides the following: eat, sleep, drink, walk, run …
What is a class?
A “class” is a data model defining the structure common to all objects that will be created from it. More concretely, we can see a class as a mold with which we will create as many objects of the same type and structure as desired.
For example, to model any person, we could write a Person class in which we define the attributes (color of eyes, color of hair, height, gender …) and methods (walking, running, eating, drinking. ..) common to all human beings.
What is an instance?
An instance is a particular representation of a class.
When creating an object, you realize what is called an “instance of the class.” That is to say that the mold is extracted in a new object that has its attributes and methods. The object thus created will like the class name.
For example, Karan Johar are instances (objects) of the class Person.
Note: a class is not an object. It is a wrong to say that a class and an object are identical.
Declaration of a class
We have just defined the vocabulary of object oriented programming. Now entering the heart of the matter, ie the declaration and instantiation of a class. We will declare a Person class which will then allow us to create as many instances (objects) of the class that we want.
Declaration syntax of a class
The following code shows one way to declare and correctly structure a class. We strongly advise you to follow these writing conventions.
Declaring a PHP class 5 <?php class MyClass { // Attributes // Constants // Methods } ?>
Here, for example what happens with our example:
Example of the Person class <?php class Person { // Attributes public $name; public $firstname ; public $DateOfBirth ; public $size; public $sex; // Constants const NUMBER_OF_ARM = 2; const NUMBER_OF_LEGS = 2; const NUMBER_OF_EYES = 2; const NUMBER_OF_FEET = 2; const NUMBER_OF_HANDS = 2; // Methods public function construct () {}
public function drinking ()
{
echo ‘The person is drinks <br/>’;
}
public function eat ()
{
echo ‘The person is eating <br/>’;
}
}
?>
As you can see, we declared five public attributes, 5 constants, 1 constructor method and two conventional methods. Detail each item.
Attributes
As we explained at the beginning of the course, the attributes are the characteristics of an object. Every person has a name, a first name, a birth date, size, sex … All these elements characterize a human being.
For this example, we declare the attributes of our public class. We will explain a tutorial in the following three levels of visibility (public, private, and protected) which can be applied to an attribute.
The public keyword can make the attribute available from outside the class. This is not a good practice to adopt but in the first tutorial we will use as is for ease of understanding.
In OOP, an attribute is neither more nor less than a variable.
Also note that we just said attributes. However, any type or no value assigned to them. So they are by default initialized to NULL.
Note: two different classes can have the same attibuts without risk of conflict.
Constants
It is also possible to declare own constants to the class. Unlike procedural programming mode, a constant is declared with the const keyword.
Note: A constant must be declared and initialized with the same time value.
The Constructor
The constructor is a special method. It is she who is called implicitly for the creation of the object (instantiation).
In our example, the builder has neither setting nor instruction. The programmer is free to define mandatory parameters to be passed to the constructor and a group of instructions to be executed in the class instantiation. We’ll go in order to simplify our example.
Note: PHP constructor overload and methods is not possible. A single time can not be defined the same method.
The Methods
Methods are actions that can be applied to an object. It’s actually functions that can take any parameters and return values or not / objects. If the shares, we advise you to name with a verb in the infinitive.
They report in the same manner as traditional functions.
Just like attributes, we declare a method with a level of visibility. The public keyword indicates that we can apply outside the class method, ie on the object itself.
Note: two different classes can have the same methods without risk of conflict.
Using classes and objects
Our class is now ready but no use just one. As we have explained above, a class is seen as a mold capable of carrying as many objects of the same type and structure as desired. We will now present the realization of a class period.
Instantiation of a class
The instantiation of a class is the phase of creating objects from this class. When you instantiate a class, use the keyword following the new class name. This statement calls the constructor method (__construct ()) that constructs the object and space in memory. The following example illustrates four different instances of the class Person.
Creating Person type objects <?php $person1 = new Person (); $person2 = new Person (); $person3 = new Person (); $person4 = new Person (); ?>
An object is actually a variable whose type is that of the class is instantiated.
Note: If we defined the parameters in the constructor method of our class, we would have the state in brackets at the instance. For example: $ person1 = new Person (‘Karan’, ‘Johar’);
Accessing attributes
Write access
We just created four objects of the same type and the same structure. In the current state, they are clones because their attributes are declared but are not initialized. We assign values to present to each of the attributes of each object.
Using the attributes of an object <?php // Set the attributes of the person 1 $person1-> name = 'Karan'; $person1-> firstname = 'Johar'; $person1-> DateOfBirth = '02 -07 to 1987 '; $person1-> size = '180'; $person1-> sex = 'M';
// Set the attributes of the person 2
$person2-> name = ‘Rajan’;
$person2-> firstname = ‘Setia’;
$person2-> DateOfBirth = ’18 -11 to 1968 ‘;
$person2-> size = ‘166’;
$person2-> sex = ‘F’;
// Set the attributes of the person 3
$person3-> name = ‘Vishal’;
$person3-> firstname = ‘Thakur’;
$person3-> DateOfBirth = ’02 -08 to 1975 ‘;
$person3-> size = ‘160’;
$person3-> sex = ‘F’;
// Set the attributes of the person 4
$person4-> name = ‘Sai’;
$person4-> firstname = ‘Ahuja’;
$person4-> DateOfBirth = ’23 -05 to 1993 ‘;
$person4-> size = ‘155’;
$person4-> sex = ‘M’;
?>
We now objects each having different Particular features.
In our example, we access directly to the value of the attribute. This is possible because we set the attribute as public. If we had said the private attribute with keywords or protected, we would have to use another mechanism to access its value or the update.
Read access
Reading the value of an attribute of an object is done in exactly the same manner as for a traditional variable. The following code shows how to display the full name of the person 1.
Displaying the name and surname of the person 1 <?php echo "Person 1: <br/> '; echo 'Name:', $person1-> name, '<br/>'; echo 'Firstname:', $person1-> firstname; ?>
Running this program produces the following result on the standard output:
Execution Result code
Person 1:
Name: Karan
Firstname: Johar
Access to constant
Access to the constants that can be read via the :: operator. The following example shows a constant reading of the Person class.
Access to a constant <?php echo 'Each person has' Person::NUMBER_OF_EYES , 'eyes.'; ?>
The implementation of this code displays the following string to standard output:
Result code execution
Each person has two eyes.
Note: If you try to redefine the value of a constant, PHP will generate an error:
Access methods
Before concluding this tutorial, it remains for us to introduce the use of methods. Their use is exactly the same as for attributes. Mind you, we defined two methods to our Person class. These are drinking () and eat (). Both display a string to standard output when executed.
Resume our previous 4 items. We simulate these four people are at the table and they dine. Simultaneously the first two people drink the contents of a glass while the two others eat. This represents by calling the drink () method on objects person1 and person2, then by calling the area () method on objects person3 and person4 .
Method call on objects <?php $person1-> drink (); $person2-> drink (); $person3-> eat (); $person4-> eat ();
?>
After execution, the result is:
Result of running the code
The person drinks
The person drinks
The person eats
The person eats
Note: As the manufacturer, if our methods had needed input parameters, we would have shown at the time of the call between the parentheses of the function.