Advanced PHP V5 object research

Source: Internet
Author: User

Advanced PHP V5 object research
This article introduces some more advanced design-oriented features of PHP V5. These include various object types that allow separation of components in the system and creation of reusable, scalable, and scalable code.


Understanding suggestion

First, we will introduce the advantages of object types and type prompts. A class defines a type. Any objects instantiated from this class belong to the type defined by this class. Therefore, use the Car class to create a Car object. If the Car class inherits the Vehicle superclass, the Car object will also be a Vehicle object. This reflects how we classify things in the real world. As you can see, the type is not just a useful method for classifying system elements. Type is the basis of object-oriented programming, because type is a guarantee of good consistent behavior. Many Design Tips come from this assurance.

The "getting started with objects in PHP V5" Display object guarantees the interface for you. When the system passes a Dictionary object, you can determine that it has the $ translations array and the summarize () method. On the contrary, correlated arrays do not provide the same level of certainty. To use the clear interface provided by the class, you need to know that your object is actually an instance of a Dictionary, rather than an imposter. You can use the instanceof operator to manually verify this. This operator is a convenient tool introduced by PHP V5 between the object instance and the class name.

Instanceof Dictionary

If the given object is an instance of the given class, the instanceof operator is parsed to true. When a Dictionary object is first encountered in a call method, you can check its type before using it.

If ($ en instanceof Dictionary ){
Print $ en-> summarize ();
}

However, if PHP V5 is used, you can build the object type check into the class or method declaration.

In "getting started with objects in PHP V5", we will focus on two classes: Dictionary, which stores terms and translations, and DictionaryIO, which exports (imports) Dictionary data from () file System. These features make it easy to send a Dictionary file to a third-party translator. A third-party translator can use its own software to edit data. Then, you can re-import the processed files. Listing 1 is a version of the Dictionary class. It accepts a DictionaryIO object and stores it for future use.

Listing 1. A version of the Dictionary class that accepts the DictionaryIO object

Class Dictionary {
Public $ translations = array ();
Public $ type = "En ";
Public $ dictio;

Function addDictionaryIO ($ dictio ){
$ This-> dictio = $ dictio;
}

Function export (){
If ($ this-> dictio ){
$ This-> dictio-> export ($ this );
}
}
}

Class DictionaryIO {
Function export ($ dict ){
Print "exporting dictionary data". "($ dict-> type )";
}
}

$ En = new Dictionary ();
$ En-> addDictionaryIO (new DictionaryIO ());
$ En-> export ();

// Output:
// Dumping dictionary data (En)

The DictionaryIO class has a single method export (), which accepts a Dictionary object and uses it to output fake messages. Now, Dictionary has two new methods: addDictionaryIO (), accepting and storing DictionaryIO objects; export (), using provided objects to export Dictionary data-or in fully implemented versions.

You may wonder why a Dictionary object not only instantiates its own DictionaryIO object, but even processes the import and export operations internally, rather than turning to the second object. One reason is that you may want a DictionaryIO object to use multiple Dictionary objects or store separate references to this object. Another reason is that by passing the DictionaryIO object to Dictionary, class switching or polymorphism can be used. In other words, you can pass the instance of the DictionaryIO subclass (such as XmlDictionaryIO) to the Dictionary and change the methods for saving and retrieving data at run time.

Figure 1 shows the Dictionary and DictionaryIO classes and their usage relationships.

As shown, there is nothing to prevent the encoder from passing completely random objects to addDictionaryIO (). Only when you run export () Will you get a similar error and find that the object already stored in $ dictio does not actually have the export () method. When using PHP V4, you must test the parameter type in this example to ensure that the encoder transmits objects of the correct type. When using PHP V5, you can deploy parameter prompts to force the object type. Add only the required object types to the parameter variables of the method declaration, as shown in Listing 2:

Listing 2. Add the object type to the parameter variables of the method declaration

Function addDictionaryIO (DictionaryIO $ dictio ){
$ This-> dictio = $ dictio;
}

Function export (){
If ($ this-> dictio ){
$ This-> dictio-> export ($ this );
}
}

Now, if the client encoder tries to pass an object of A type error to addDictionaryIO (), the PHP engine will throw a fatal error. Therefore, the type prompt makes the code safer. Unfortunately, the prompt is only valid for the object, so the string or integer cannot be required in the parameter list. You must manually test these original types.

Even though addDictionaryIO () can obtain the correct object type, this method cannot be called first. The export () method tests the existence of the $ dictio attribute in the export () method to avoid errors. However, you may want to be stricter and require that the DictionaryIO object be passed to the constructor to ensure that $ dictio is always filled.

Call override method

In listing 3, XmlDictionaryIO integrates DictionaryIO. While DictionaryIO writes and reads serialized data, XmlDictionaryIO operates XML and can be shared with third-party applications. XmlDictionaryIO can overwrite its parent method (import () and export (), or you can choose not to provide your own implementation (path ()). If the client calls the path () method in the XmlDictionaryIO object, the path () method implemented in DictionaryIO is called.

In fact, you can use both methods. Override the method and call the parent implementation. To this end, use the New Keyword parent. Parent is used by the range resolution operator and the name of the discussed method. For example, assume that XmlDictionaryIO needs to use the xml directory in the current working directory (if one is available); otherwise, it should use the default path generated by the parent DictionaryIO class, as shown in listing 3:

Listing 3. XmlDictionaryIO uses the xml directory or the default path generated by the DictionaryIO class

Class XmlDictionaryIO extends DictionaryIO {

Function path (Dictionary $ dictionary, $ ext ){
$ Sep = DIRECTORY_SEPARATOR;
If (is_dir (". {$ sep} xml ")){
Return ". {$ sep} xml {$ sep} {$ dictionary-> getType ()}. $ ext ";
}
Return parent: path ($ dictionary, $ ext );
}
//...

You can see that this method checks the local xml directory. If the test fails, it uses the parent keyword to assign it to the parent method.

There are 3 pages in this news. Currently, there are 3 pages in 1st.


Subclass and constructor Methods

The parent keyword is particularly important in constructor methods. If the constructor is not defined in the subclass, the parent constructor means that you are explicitly called. If no constructor method is created in the subclass. It is your responsibility to call the constructor of the parent class and pass any parameters, as shown in Listing 4:

Listing 4. Invoking the parent class's constructor

Class SpecialDictionary extends Dictionary {
Function _ construct ($ type, DictionaryIO $ dictio, $ additional ){
// Do something with $ additional
Parent: :__ construct ($ type, $ dictio );
}
}


Abstract classes and Methods

Although it is completely legal to provide default actions in the parent class, this may not be the most clever method. For starters, you must rely on the sub-class authors to understand that they must implement import () and export () to create classes in the broken state. In addition, the DictionaryIO class is actually a brother, not a parent or child. XmlDictionaryIO is not a special case of DictionaryIO; instead, it is an alternative implementation.

PHP V5 Allows defining partial implemented classes. Its main role is to specify core interfaces for its children. This type must be declared as abstract.


Abstract class DictionaryIO {}


Abstract classes cannot be instantiated. You must create a subclass (that is, create a class that inherits it) and an instance that inherits the subclass. Standard and abstract methods can be declared in abstract classes, as shown in listing 5. Abstract Method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.