English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to write code in an object-oriented way in PHP.
Object-oriented programming (OOP) is a programming model based on the concepts of classes and objects. Unlike procedural programming, which focuses on writing procedures or functions that operate on data, object-oriented programming focuses on creating objects that contain both data and functions.
Compared to conventional or procedural programming, object-oriented programming has many advantages. The most important ones are listed as follows:
It provides a clear modular structure for the program.
It helps you adhere to the 'Don't Repeat Yourself' (DRY) principle, making your code easier to maintain, modify, and debug.
It allows for the creation of more complex behaviors with less code, shorter development time, and high reusability.
The following sections will describe how classes and objects work in PHP.
Tip:A program written in procedural programming style means that the program is composed of one or more procedures. A procedure is a set of programming statements that execute together to perform a specific task.
Tip:The idea behind the 'Don't Repeat Yourself' (DRY) principle is to reduce code repetition by abstracting out commonly used code in an application and placing it in a single location for reuse rather than repetition.
Classes and objects are two main aspects of object-oriented programming. A class is a collection of independent variables and functions that work together to perform one or more specific tasks, while an object is a single instance of a class.
A class acts as a template or blueprint from which many individual objects can be created. When creating a single object, although some properties of each object may have different values, they inherit the same general properties and behaviors.
For example, consider a class as the blueprint of a house. The blueprint itself is not the house, but the detailed plan of the house. And an object is like the actual house built according to this blueprint. We can build several houses with the same blueprint, but each house may have different paint, interior, and family inside, as shown in the figure below.
A class can be declared using the class keyword, followed by the name of the class and a pair of curly braces ({}), as shown in the following example.
Let's create a PHP file named Recangle.php and place the following sample code in it, so that we can separate our class code from the rest of the program. Then, we can use it anywhere we need by simply including the Recangle.php file.
<?php class Rectangle { //Declare properties public $length = 0; public $width = 0; //method to calculate the perimeter public function getPerimeter(){ return (2 * ($this->length + $this->width)); } //method to calculate the area public function getArea(){ return ($this->length * $this->width); } } ?>
The public keyword before the properties and methods in the above example is aAccess Modifiersmeans that the property or method can be accessed from anywhere. We will learn more about this in the later part of this chapter.
Note:In terms of syntax, variables in a class are called properties, while functions are called methods. Additionally, class names are usually written in PascalCase, which means that each connected word starts with an uppercase letter (e.g., MyClass).
Create another PHP file named test.php and place the following code in it.
<?php //contains class definition class Rectangle { //Declare properties public $length = 0; public $width = 0; //method to calculate the perimeter public function getPerimeter(){ return (2 * ($this->length + $this->width)); } //method to calculate the area public function getArea(){ return ($this->length * $this->width); } } //Create a new object from the Rectangle class $obj = new Rectangle; //Get object property values echo $obj->length; // Output: 0 echo $obj->width; // Output: 0 //$obj = new Square(); length = $obj-Set object property values 30; length = $obj-width = $obj 20; //Read the object property values again to display changes echo $obj->length; // Output: 30 echo "<br>"; echo $obj->width; // Output: 20 //Invoke object method echo $obj->getPerimeter(); // Output: 100 echo "<br>"; echo $obj-getArea(); // Output: 600 ?>Test to see‹/›
The arrow symbol (-)is an OOP construct used to access the properties and methods contained in the given object. While the pseudo-variable $this provides a reference to the calling object (i.e., the object to which the method belongs).
The true power of object-oriented programming becomes evident when using multiple instances of the same class, as shown in the following example:
<?php //contains class definition class Rectangle { //Declare properties public $length = 0; public $width = 0; //method to calculate the perimeter public function getPerimeter(){ return (2 * ($this->length + $this->width)); } //method to calculate the area public function getArea(){ return ($this->length * $this->width); } } //Create multiple objects from the Rectangle class length = $obj1 = new Rectangle; length = $obj2 = new Rectangle; //Call the methods of two objects echo $obj1-getArea(); //Output: 0 echo $obj2-getArea(); //Output: 0 //Set $obj1Property value length = $obj1-Set object property values 30; length = $obj1-width = $obj 20; //Set $obj2Property value length = $obj2-Set object property values 35; length = $obj2-width = $obj 50; //Call the methods of two objects again echo $obj1-getArea(); //Output:600 echo "<br>"; echo $obj2-getArea(); //Output:1750 ?>Test to see‹/›
As shown in the above example, calling the getArea() method on different objects causes the method to operate on different datasets. Each object instance is completely independent, with its own properties and methods, so even if they belong to the same class, they can be operated on independently.
To simplify object-oriented programming, PHP provides some magic methods that are automatically executed when certain operations occur in an object.
For example, the magic method __construct() (also called the constructor) is automatically executed every time a new object is created. Similarly, the magic method __destruct() (also called the destructor) is automatically executed when the object is destroyed. After the object is destroyed, the destructor will clear all resources allocated to the object.
<?php class MyClass { // Constructor public function __construct() { echo ' Class "' . __CLASS__ . '" has started<br> } // Destructor public function __destruct(){ echo 'Class '. __CLASS__ . '" has been destroyed<br>'; } } //Create a new object $obj = new MyClass; //Output message at the end of the file echo "Reached the end of the file."; ?>Test to see‹/›
The PHP code in the above example will produce the following output:
Class "MyClass" has been started Reached the end of the file. Class "MyClass" has been destroyed
The destructor will be automatically called at the end of the script. However, to explicitly trigger the destructor, you can use the PHP unset() function to destroy the object, as shown below:
<?php class MyClass { // Constructor public function __construct() { echo ' Class "' . __CLASS__ . '" has started<br> } // Destructor public function __destruct(){ echo 'Class '. __CLASS__ . '" has been destroyed<br>'; } } //Create a new object $obj = new MyClass; // Destroy the object unset($obj); //Output message at the end of the file echo "Reached the end of the file."; ?>Test to see‹/›
Now, the PHP code in the above example will produce the following output:
Class "MyClass" has been started Class "MyClass" has been destroyed Reached the end of the file.
Tip:After the script is completed, PHP will automatically clear all resources allocated during execution, such as closing database connections, destroying objects, etc.
Note:__CLASS__ is aMagic constantscontains the name of the class it is in. If it occurs outside the class, it is empty.
A class can use the extends keyword to inherit properties and methods from another class. The process of extendability is called inheritance. This may be the most powerful reason behind the use of the object-oriented programming model.
<?php //contains class definition class Rectangle { //Declare properties public $length = 0; public $width = 0; //method to calculate the perimeter public function getPerimeter(){ return (2 * ($this->length + $this->width)); } //method to calculate the area public function getArea(){ return ($this->length * $this->width); } } //define a new class based on the existing class definition class Square extends Rectangle { //method to test if the rectangle is also a square public function isSquare(){ if($this->length == $this->width){ return true; // } else { Square //return false; } } } //Not a square Create a new object from the Square class // $obj = new Square(); length = $obj-Set object property values 20; length = $obj-width = $obj 20; // Invoke object method if($obj-isSquare()){ echo "The area of the square is"; } else { echo "The area of the rectangle is"; }; echo $obj-getArea(); ?>Test to see‹/›
The PHP code in the above example will produce the following output:
The area of the square is 400
As you can see in the example above, although the Square class definition does not explicitly include the getArea() method or explicitly include the $length and $width properties, the instances of the Square class can use them because they inherit from the parent Rectangle class.
Tip:Since subclasses are derived from parent classes, they are also called derived classes, and their parent classes are called base classes.
When using a class, you can even use visibility keywords to limit access to its properties and methods for better control. There are three visibility keywords (from most visible to least visible): public, protected, private, which determine how and from where properties and methods can be accessed and modified.
public - Public properties or methods can be accessed from any location inside and outside the class. This is the default visibility of all class members in PHP.
protected - Protected properties or methods can only be accessed from the class itself or subclasses or inherited classes (i.e., classes that extend the class).
private - Private properties or methods can only be accessed from the class that defines them. Even subclasses or inherited classes cannot access private properties or methods.
The following example will show you how visibility actually works:
<?php //Class definition class Automobile { //Declare properties public $fuel; protected $engine; private $transmission; } class Car extends Automobile { // Constructor public function __construct() { echo ' Class "' . __CLASS__ . '" has started<br> } } //Create an object from the Automobile class $automobile = new Automobile(); //Attempt to set the property of the $automobile object $automobile-fuel = 'Petrol'; // ok $automobile->engine = '1500 cc'; // fatal error $automobile->transmission = 'Manual'; // fatal error //Create an object from the Car class $car = new Car; //Attempt to set $car object property $car->fuel = 'Diesel'; // ok $car->engine = '2200 cc'; // fatal error $car->transmission = 'Automatic'; // undefined ?>
In addition to visibility, properties and methods can also be declared as static (static), which makes them accessible without an instance of the class. Static properties and methods can be accessed using the scope resolution operator (::) as shown below: ClassName::$property and ClassName::method().
Although static methods can be used, static properties declared in the class cannot be accessed through an object of the class, as shown in the following example:
<?php //Class definition class HelloClass { //Declare static property public static $greeting = "Hello World!"; //Declare static method public static function sayHello(){ echo self::$greeting; } } //Attempt to access static properties and methods directly echo HelloClass::$greeting; //Output: Hello World! HelloClass::sayHello(); //Output: Hello World! //Attempt to access static properties and methods through an object $hello = new HelloClass; echo $hello->greeting; // Strict Warning $hello->sayHello(); //Output: Hello World! ?>
In the example above, the keyword self represents the 'current class'. It must never start with a dollar sign ($) and always starts with the :: operator (such as self :: $ name).
The self keyword is different from the this keyword, which represents the 'current object' or 'the current instance of the class'. This keyword always starts with a dollar sign ($) followed by-> operators (such as $ this-> name()).
Note:Since static methods can be called without a class instance (i.e., an object), the pseudo-variable $this is not available in methods declared as static.
We hope you now understand the basic concepts of object-oriented programming. You will find more examples of OOP in the PHP and MySQL database sections.