Class và object trong php

In this tutorial you will learn how khổng lồ write code in object-oriented style in PHPhường.Quý khách hàng vẫn xem: Learn php

What is Object Oriented Programming

Object-Oriented Programming (OOP) is a programming model that is based on the concept of classes và objects. As opposed to procedural programming where the focus is on writing procedures or functions that perkhung operations on the data, in object-oriented programming the focus is on the creations of objects which contain both data & functions together.

Bạn đang xem: Class và object trong php

Object-oriented programming has several advantages over conventional or procedural style of programming. The most important ones are listed below:

It provides a clear modular structure for the programs.It helps you adhere to the "don"t repeat yourself" (DRY) principle, and thus make your code much easier to maintain, modify and debug.It makes it possible to create more complicated behavior with less code & shorter development time và high degree of reusability.

The following sections will describe how classes and objects work in PHP..

Tip: A program written in procedural programming style, meaning a program is made of one or more procedures. Whereas, a procedure is a mix of programming statements that together, perkhung a specific task.

Tip: The idea behind Don"t Repeat Yourself (DRY) principle is reducing the repetition of code by abstracting out the code that are common for the application & placing them at a single place and reuse them instead of repeating it.

Understanding Classes and Objects

Classes và objects are the two main aspects of object-oriented programming. A class is a self-contained, independent collection of variables and functions which work together khổng lồ perform one or more specific tasks, while objects are individual instances of a class.

A class acts as a template or blueprint from which lots of individual objects can be created. When individual objects are created, they inherit the same generic properties & behaviors, although each object may have sầu different values for certain properties.

For example, think of a class as a blueprint for a house. The blueprint itself is not a house, but is a detailed plan of the house. While, an object is like an actual house built according lớn that blueprint. We can build several identical houses from the same blueprint, but each house may have different paints, interiors & families inside, as shown in the illustration below.


A class can be declared using the class keyword, followed by the name of the class & a pair of curly braces (), as shown in the following example.

Let"s create a PHPhường tệp tin named Rectangle.php và put the following example code inside it so that our class code should be separated from rest of the program. We can then use it wherever it"s needed by simply including the Rectangle.php tệp tin.

length + $this->width)); } // Method khổng lồ get the area public function getArea() return ($this->length * $this->width); }?>The public từ khoá before the properties & methods in the example above sầu, is an access modifier, which indicates that this property or method is accessible from anywhere. We will learn more about this a little later in this chapter.

Note: Syntactically, variables within a class are called properties, whereas functions are called methods. Also class names conventionally are written in PascalCase i.e. each concatenated word starts with an uppercase letter (e.g. MyClass).

Once a class has been defined, objects can be created from the class with the new keyword. Class methods và properties can directly be accessed through this object instance.

Create another PHP file name chạy thử.php & put the following code inside it.

length; // 0utput: 0echo $obj->width; // 0utput: 0 // Set object properties values$obj->length = 30;$obj->width = 20; // Read the object properties values again to lớn show the changeecho $obj->length; // 0utput: 30emang đến $obj->width; // 0utput: đôi mươi // Gọi the object methodsemang đến $obj->getPerimeter(); // 0utput: 100emang đến $obj->getArea(); // Output: 600?> The arrow symbol (->) is an OOPhường construct that is used to access contained properties & methods of a given object. Whereas, the pseudo-variable $this provides a reference khổng lồ the calling object i.e. the object to which the method belongs.

The real power of object oriented programming becomes evident when using multiple instances of the same class, as shown in the following example:

getArea(); // Output: 0emang đến $obj2->getArea(); // Output: 0 // Set $obj1 properties values$obj1->length = 30;$obj1->width = 20; // Set $obj2 properties values$obj2->length = 35;$obj2->width = 50; // gọi the methods of both the objects againemang đến $obj1->getArea(); // Output: 600echo $obj2->getArea(); // Output: 1750?>As you can see in the above example, calling the getArea() method on different objects causes that method lớn operate on a different mix of data. Each object instance is completely independent, with its own properties and methods, & thus can be manipulated independently, even if they"re of the same class.

Xem thêm: 10+ Phần Mềm Uchat - Hướng Dẫn Cài Đặt Chat Trên Website Wordpress

Using Constructors and Destructors

To make the object-oriented programming easier, PHP. provides some magic methods that are executed automatically when certain actions occur within an object.

For example, the magic method __construct() (known as constructor) is executed automatically whenever a new object is created. Similarly, the magic method __destruct() (known as destructor) is executed automatically when the object is destroyed. A destructor function cleans up any resources allocated lớn an object once the object is destroyed.

"; } // Destructor public function __destruct() eđến "The class "" . __CLASS__ . "" was destroyed."; } // Create a new object$obj = new MyClass; // Output đầu ra a message at the over of the fileemang lại "The kết thúc of the tệp tin is reached.";?>A destructor is called automatically when a scripts ends. However, to lớn explicitly trigger the destructor, you can destroy the object using the PHPhường unset() function, as follow:

"; } // Destructor public function __destruct() eđến "The class "" . __CLASS__ . "" was destroyed."; } // Create a new object$obj = new MyClass; // Destroy the objectunset($obj); // Output a message at the end of the fileemang đến "The end of the file is reached.";?> Tip: PHPhường automatically clean up all resources allocated during execution when the script is finished, e.g. closing database connections, destroying objects, etc.

Note: The __CLASS__ is a magic constant which contains the name of the class in which it is occur. It is empty, if it occurs outside of the class.

Extending Classes through Inheritance

Classes can inherit the properties and methods of another class using the extends từ khoá. This process of extensibility is called inheritance. It is probably the most powerful reason behind using the object-oriented programming mã sản phẩm.

length == $this->width) return true; // Square else return false; // Not a square }} // Create a new object from Square class$obj = new Square; // Set object properties values$obj->length = 20;$obj->width = 20; // Gọi the object methodsif($obj->isSquare()) echo "The area of the square is "; else emang lại "The area of the rectangle is ";;emang lại $obj->getArea();?>As you can see in the above sầu example, even though the class definition of Square doesn"t explicitly contain getArea() method nor the $length và $width property, instances of the Square class can use them, as they inherited from the parent Rectangle class.

Tip: Since a child class is derived from a parent class, it is also referred khổng lồ as a derived class, và its parent is called the base class.

Controlling the Visibility of Properties và Methods

When working with classes, you can even restrict access to lớn its properties và methods using the visibility keywords for greater control. There are three visibility keywords (from most visible to lớn least visible): public, protected, private, which determines how và from where properties & methods can be accessed và modified.

public — A public property or method can be accessed anywhere, from within the class and outside. This is the mặc định visibility for all class members in PHP..protected — A protected property or method can only be accessed from within the class itself or in child or inherited classes i.e. classes that extends that class.private — A private property or method is accessible only from within the class that defines it. Even child or inherited classes cannot access private properties or methods.

The following example will show you how this visibility actually works:

"; }} // Create an object from Autothiết bị di động class$autoMobile = new Automobile; // Attempt to lớn mix $autoMobile object properties$automobile->fuel = "Petrol"; // ok$automobile->engine = "1500 cc"; // fatal error$automobile->transmission = "Manual"; // fatal error // Create an object from Car class$car = new Car; // Attempt lớn mix $oto object properties$car->fuel = "Diesel"; // ok$car->engine = "2200 cc"; // fatal error$car->transmission = "Automatic"; // undefined?>

Static Properties và Methods

In addition khổng lồ the visibility, properties & methods can also be declared as static, which makes them accessible without needing an instantiation of the class. Static properties & methods can be accessed using the scope resolution operator (::), like this: ClassName::$property and ClassName::method().

A property declared as static cannot be accessed via the object of that class though a static method can be, as demonstrated in the following example:

The keyword self in the above sầu example means "the current class". It is never preceded by a dollar sign ($) and always followed by the :: operator (e.g. self::$name).

The self keyword is different from the this keyword which means "the current object" or "the current instance of a class". The this từ khoá is always preceded by a dollar sign ($) và followed by the -> operator (e.g. $this->name).

Note: Since static methods can be called without an instance of a class (i.e. object), the pseudo-variable $this is not available inside the method declared as static.