Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
để thực hiện tất cả các nhiệm vụ cần thiết. Lập trình hướng đối tượng đi một chặng đường dài hướng tới việc loại bỏ khả năng cho các lỗi này bằng cách cung cấp phương pháp đặc biệt, được gọi là nhà xây dựng và hàm hủy, tự động hoá việc tạo ra đối tượng và các quá trình tiêu hủy. | 148 CHAPTER 6 OBJECT-ORIENTED PHP Constructors and Destructors Often you ll want to execute a number of tasks when creating and destroying objects. For example you might want to immediately assign several fields of a newly instantiated object. However if you have to do so manually you ll almost certainly forget to execute all of the required tasks. Object-oriented programming goes a long way toward removing the possibility for such errors by offering special methods called constructors and destructors that automate the object creation and destruction processes. Constructors You often want to initialize certain fields and even trigger the execution of methods found when an object is newly instantiated. There s nothing wrong with doing so immediately after instantiation but it would be easier if this were done for you automatically. Such a mechanism exists in OOP known as a constructor. Quite simply a constructor is defined as a block of code that automatically executes at the time of object instantiation. OOP constructors offer a number of advantages Constructors can accept parameters which are assigned to specific object fields at creation time. Constructors can call class methods or other functions. Class constructors can call on other constructors including those from the class parent. This section reviews how all of these advantages work with PHP 5 s improved constructor functionality. Note PHP 4 also offered class constructors but it used a different more cumbersome syntax than that used in version 5. Version 4 constructors were simply class methods of the same name as the class they represented. Such a convention made it tedious to rename a class. The new constructor-naming convention resolves these issues. For reasons of compatibility however if a class is found to not contain a constructor satisfying the new naming convention that class will then be searched for a method bearing the same name as the class if located this method is considered the constructor.