with the new language features of PHP V5, the maintainability and reliability of the code can be greatly improved. By reading this article, you will learn how to use these new features to migrate code developed in PHP V4 to PHP V5.
PHP V5 has made significant improvements on the basis of PHP V4. The new language features make it easier to build reliable class libraries and maintain class libraries. In addition, rewriting the standard library helps make PHP more consistent with its Web language, such as the Java™ programming language. Let's take a look at some of the new object-oriented features of PHP and learn how to migrate existing PHP V4 code to PHP V5.
First, learn how the new language features and how PHP's creation program changed the way you create objects with PHP V4. The idea with V5 is to create an industrial-grade language for WEB application development. That means understanding the limitations of PHP V4 and then extracting the known good language architectures from other languages (such as Java,, C# C++ , Ruby, and Perl) and incorporating them into PHP.
The first and most important new feature is access protection for the class's methods and instance variables-- public , protected and the private keyword. This new feature enables class designers to maintain control over the intrinsic nature of the class, while telling the class's consumer which classes can and which classes are not reachable.
In PHP V4, all the code is public . In PHP V5, class designers can declare which code is externally visible () public and which code is visible only to the inside of the class ( private ) or only to subclasses of the class ( protected ). Without these access controls, the work of developing code or distributing code into libraries in large teams is blocked because the consumer of those classes is likely to use the wrong method or access code that should be a private member variable.
Another big new feature is the keyword interface and abstract , these two keywords allow for contract programming. contract programming means that a class provides a contract to another class-in other words: "This is the work I'm going to do, you don't need to know how it's done." All classes that implement interface follow the contract. All interface users agree to use only the methods specified in interface. The abstract keyword makes it easy to use interfaces, which I'll explain later.
These two key features-access control and contract programming-allow large coders teams to work more smoothly with large code libraries. These features also enable the IDE to provide a richer set of language intelligence features. This article has not only explained several migration issues, but also spent some time explaining how to use these new primary language features.
Access control
To demonstrate the new language features, I used a class named Configuration . This simple class contains configuration items for the WEB application-for example, a path to the picture directory. Ideally, this information will be present in a file or database. Listing 1 shows a simplified version.
Listing 1. ACCESS.PHP4
_items[' imgpath '] = ' images '; } function Get ($key) { return $this->_items[$key]; }} $c = new Configuration (), Echo ($c->get (' Imgpath '). " \ n ");? >
This is a completely orthodox PHP V4 class. A member variable holds a list of configuration items, constructs a program mount item, and then returns the value of the get() item by means of an access method named.
After you run the script, the following code is displayed on the command line:
% PHP access.php4images%
Very good! This result means that the code is working properly and the imgpath value of the configuration item is set and read normally.
The first step in converting this class to PHP V5 is to rename the constructor. In PHP V5, the method of initializing an object (constructor) is called __construct . This small change is shown below.
Listing 2. ACCESS1.PHP5
_items[' imgpath '] = ' images '; } function Get ($key) { return $this->_items[$key]; }} $c = new Configuration (), Echo ($c->get (' Imgpath '). " \ n ");? >
This change is not big. Just move to the PHP V5 convention. The next step is to add access control to the class to ensure that the class's consumer cannot read and write the $_items member variables directly. This change is shown below.
Listing 3. ACCESS2.PHP5
_items[' imgpath '] = ' images '; } Public function Get ($key) { return $this->_items[$key]; }} $c = new Configuration (), Echo ($c->get (' Imgpath '). " \ n ");? >
If the object's consumer has to access the item array directly, access is denied because the array is marked as private . Fortunately, the user Discovery get() method can provide popular Read permissions.
To illustrate how protected permissions are used, I need another class, which must inherit from the class Configuration . I call that class DBConfiguration , and assume that the class will read the configuration values from the database. This setting is shown below.
Listing 4. access3.php
Load (); } protected function Load () {} public function get ($key) { return $this->_items[$key]; }} Class Dbconfiguration extends configuration{ protected function Load () { $this->_items[' imgpath '] = ' Images '; }} $c = new Dbconfiguration (), Echo ($c->get (' Imgpath '). \ n ");? >
This list shows the protected correct usage of the keyword. The base class defines a method named. load() Subclasses of this class will overwrite the load() method to add data to the items table. load()method is an internal method on a class and its subclasses, so the method is not visible to all external users. If the keyword is all private , the load () method cannot be overwritten.
I don't really like this design, but this design is chosen because the class has to be DBConfiguration able to access the item array. I want to continue to Configuration have the item array fully maintained by the class so that when additional subclasses are added, those classes will not need to know how to maintain the item array. I made the following changes.
Listing 5. ACCESS4.PHP5
Load (); } protected function Load () {} protected function Add ($key, $value) { $this->_items[$key] = $value; } Public function Get ($key) { return $this->_items[$key]; }} Class Dbconfiguration extends configuration{ protected function Load () { $this->add (' Imgpath ', ' images ') ; }} $c = new Dbconfiguration (), Echo ($c->get (' Imgpath '). \ n ");? >
The item array can now be private because subclasses use protected add() methods to add configuration items to the list. Configurationclass can change the way a configuration item is stored and read without having to consider its subclasses. As long as load() add() the method runs in the same way, the subclass should not have a problem.
For me, adding access control is the main reason to consider moving to PHP V5. Is it because Grady Booch that PHP V5 is one of the four object-oriented languages? No, because I once accepted a task to maintain 100KLOC C++ code in which all methods and members are defined as public. It took me three days to clear these definitions and, during the purge process, significantly reduced the number of errors and improved maintainability. Why? Because there is no access control, it is impossible to know how an object uses other objects, and it is impossible to make any changes without knowing what is going to break the tide. Use C++ , at least I have a compile program available. PHP is not equipped with a compiler, so this type of access control becomes increasingly important.
Contract programming
The next important feature to take advantage of when migrating from PHP V4 to PHP V5 is the support for contract programming through interfaces, abstract classes, and methods. Listing 6 shows a version of the Configuration class in which PHP V4 coders try to build a basic interface without using keywords at all interface .
listing 6. INTERFACE.PHP4
Load (); } function load () {} function get ($key) { return $this->_items[$key]; }} Class Dbconfiguration extends configuration{ function load () { $this->_items[' imgpath '] = ' images '; }} $c = new Dbconfiguration (), Echo ($c->get (' Imgpath '). \ n ");? >
The manifest begins in a small IConfiguration class that defines the Configuration interfaces provided by all classes or derived classes. This interface defines the contract between the class and all its users. The contract declares IConfiguration that all classes implemented must have get() methods and IConfiguration that all users must persist in using only the get() methods.
The following code is run in PHP V5, but it is best to use the provided interface system, as shown below.
Listing 7. INTERFACE1.PHP5
Get (' Imgpath '). " \ n ");? >
On the one hand, the reader can understand the health more clearly, on the other hand, a single class can implement multiple interfaces. Listing 8 shows how to extend a Configuration class to implement Iterator an interface, which is an internal interface for PHP.
Listing 8. INTERFACE2.PHP5
Load (); } protected function Load () {} protected function Add ($key, $value) { $this->_items[$key] = $value; } Public function Get ($key) { return $this->_items[$key]; } Public Function Rewind () {Reset ($this->_items);} Public function current () {return current ($this->_items);} Public Function key () {return key ($this->_items);} Public function Next () {return next ($this->_items);} Public Function valid () {return ($this->current ()!== false);}} Class Dbconfiguration extends Configuration { ...} $c = new Dbconfiguration (), foreach ($c as $k = = $v) {echo ($k. "=". $v. " \ n "); }?>
IteratorInterfaces enable all classes to appear to be arrays of their users. As you see at the end of the script, you can use the foreach operator to reiterate Configuration all the configuration items in the object. PHP V4 does not have this functionality, but you can use it in various ways in your application.
The advantage of interface mechanisms is that contracts can be quickly lumped together without the need to implement any method. The final stage is to implement the interface, and you must implement all the specified methods. Another helpful new feature in PHP V5 is an abstract class that uses an abstract class to easily implement the core of an interface with a base class, and then use that interface to create an entity class.
Another use of an abstract class is to create a base class for multiple derived classes, in which the base class is never instantiated. For example, when DBConfiguration and when Configuration they exist, they can only be used DBConfiguration . A Configuration class is just a base class-an abstract class. Therefore, you can use abstract the keyword to force the behavior, as shown below.
listing 9. ABSTRACT.PHP5
Load (); } Abstract protected function load (); Public function Get ($key) { return $this->_items[$key]; }} Class Dbconfiguration extends configuration{ protected function Load () { $this->_items[' imgpath '] = ' Images '; }} $c = new Dbconfiguration (), Echo ($c->get (' Imgpath '). \ n ");? >
All attempts to instantiate an Configuration object of type are now faulted because the system considers the class to be abstract and incomplete.
Static methods and members
Another important new feature in PHP V5 is that it supports the use of static members and methods for classes. By using this feature, you can use the popular singleton mode. This pattern Configuration is ideal for classes because the application should have only one configuration object.
Listing 10 shows the PHP V5 version of the Configuration class as a single example.
List of the ten. STATIC.PHP5
_items[' imgpath '] = ' images '; } Public Function __get ($key) { return $this->_items[$key]; }} Echo (Configuration::get ()->{' Imgpath '}. " \ n ");? >
staticKeywords have many uses. Consider using this keyword when you need to access some global data for all objects of a single type.
Magic Method
Another big new feature in PHP V5 is the ability to support Magicmethod, which enables objects to quickly change an object's interface-for example, to Configuration add member variables for each configuration item in an object. No need get() to use a method, just look for a special item to treat it as an array, as shown below.
List one by one . MAGIC.PHP5
_items[' imgpath '] = ' images '; } function __get ($key) { return $this->_items[$key]; }} $c = new Configuration (); Echo ($c->{' Imgpath '}. " \ n ");? >
In this case, I've created a new __get() method that calls this method whenever the consumer looks for a member variable on the object. The code in the method then uses the item array to find the value and returns the value as if there was a member variable dedicated to that keyword. Assuming that the object is an array, at the end of the script, you can see that using Configuration the object is as simple as looking for imgpath a value.
When migrating from PHP V4 to PHP V5, you must be aware of these language features that are completely unavailable in PHP V4, and you must re-validate your classes to see how you can use them.
Abnormal
Finally, introduce the new exception mechanism in PHP V5 to end this article. Exceptions provide a completely new way to consider error handling. All programs inevitably generate errors-no files found, low memory, and so on. If you do not use an exception, you must return an error code. Take a look at the PHP V4 code below.
List of FILE.PHP4.
0, data = array ()//Data here );} function Readconfig ($path) { if ($path = = null) return-1; $fh = fopen ($path, ' R '); if ($fh = = null) return-2; while (!feof ($fh)) { $l = fgets ($fh); $ec = ParseLine ($l); if ($ec [' ERROR ']! = 0) return $ec [' Error ']; } Fclose ($FH); return 0;} $e = Readconfig (' myconfig.txt '); if ($e! = 0) echo ("There is an error (". $e. ") \ n ");? >
This standard file I/O code reads a file, retrieves some data, and returns an error code if any errors are encountered. For this script, I have two questions. The first one is the error code. What is the meaning of these error codes? To find out what these error codes mean, you must create another system to map these error codes into a meaningful string. The second problem is parseLine that the return result is very complex. I just need it to return the data, but it must actually return the error code and data. Most engineers (myself included) are often lazy, returning only data, ignoring errors, because errors are difficult to manage.
Listing 13 shows how clear the code is when you use the exception.
List of file.php5.
I don't need to worry about the error code because the exception contains an incorrect descriptive text. I also don't have to think about how to trace the parseLine error code from the return, because if an error occurs, the function will only throw an error. The stack extends to the nearest try/catch block, which is at the bottom of the script.
The exception mechanism will radically change the way code is written. You don't have to manage the error codes and mappings that make people headache, you can focus on the errors you want to handle. Such code is easier to read and maintain, and I would like to say that even encouraging you to add error-handling mechanisms usually brings benefits.
Conclusion
The addition of new object-oriented features and exception handling provides a strong justification for migrating code from PHP V4 to PHP V5. As you can see, the upgrade process is not difficult. The syntax for extending to PHP V5 feels like PHP. Yes, these grammars come from languages like Ruby, but I think they work very well together. And these languages extend the scope of PHP from a scripting language for small sites to a language that can be used to complete enterprise-class applications.
http://www.bkjia.com/PHPjc/735121.html www.bkjia.com true http://www.bkjia.com/PHPjc/735121.html techarticle with the new language features of PHP V5, the maintainability and reliability of the code can be greatly improved. By reading this article, you'll learn how to take advantage of these new features to move code developed with PHP V4 .