Advanced PHP V5 Object Research _php Tutorial

Source: Internet
Author: User
Advanced PHP V5 Object Research
This article describes some of the more advanced design-oriented features of PHP V5. These include various object types that allow components in the system to be detached from one another, creating reusable, extensible, and scalable code.


GRASP the hint

Let's start by describing the benefits of object types and type hints. A class defines a type. Any object instantiated from this class belongs to the type defined by that 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 the way we classify things in the real world. But as you'll see, the type is not just a useful way to classify system elements. Types are the basis of object-oriented programming because types are a guarantee of well-consistent behavior. Many design techniques come from this assurance.

"Getting Started with objects in PHP V5" shows you how the interface is guaranteed. When the system passes the Dictionary object, you can determine that it has $translations array and summarize () method. In contrast, associative arrays do not provide the same level of certainty. To take advantage of the clear interface provided by the class, you need to know that your object is actually an instance of Dictionary, not a imposter. You can manually verify this with the instanceof operator, which is a handy tool that PHP V5 introduces between the object instance and the class name.

instanceof Dictionary

If the given object is an instance of a given class, the instanceof operator resolves to true. The first time you encounter a Dictionary object in the calling method, you can check its type before you use it.

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

However, if you use PHP V5, you can build object type checking into a class or method declaration.

In "Getting Started with objects in PHP V5," Focus on two classes: Dictionary, which stores terminology and translations, Dictionaryio, which exports (imports) the Dictionary data from (to) the file system. These features make it easy to send Dictionary files to third-party translators, and third-party translators can use their own software to edit data. Then, you can re-import the processed files. Listing 1 is a version of the Dictionary class that accepts a Dictionaryio object and stores it for future use.

Listing 1. Accepts a version of the Dictionary class for a 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 false messages. Now, Dictionary has two new methods: Adddictionaryio (), accepting and storing Dictionaryio objects, export (), exporting Dictionary data using the provided object--or in a fully implemented version.

You may wonder why the Dictionary object not only instantiates its own Dictionaryio object, or even handles the import export operation internally, without resorting to a second object at all. One reason is that you might want a Dictionaryio object to use more than one Dictionary object, or you want to store a separate reference to that object. Another reason is that you can take advantage of class switching or polymorphism by passing Dictionaryio objects to Dictionary. In other words, you can pass an instance of the Dictionaryio subclass (such as Xmldictionaryio) to Dictionary and change the way the runtime saves and retrieves data.

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

As shown, there is nothing to prevent the encoder from passing a completely random object to Adddictionaryio (). A similar error is obtained only when you run export (), and it is found that objects that are already stored in the $dictio do not actually have the export () method. When using PHP V4, you must test the parameter types in this example to absolutely ensure that the encoder passes the correct type of object. When using PHP V5, you can deploy parameter hints to enforce object types. Add only the desired object type to the parameter variable of the method declaration, as shown in Listing 2:

Listing 2. To add an object type to a parameter variable in a 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 the wrong type to Adddictionaryio (), the PHP engine throws a fatal error. Therefore, type hints make your code more secure. Unfortunately, the hint is only valid for the object, so you cannot ask for a string or integer in the argument list. These primitive types must be tested manually.

Even if Adddictionaryio () is guaranteed to get the correct object type, there is no guarantee that the method will be called first. The export () method tests the existence of $dictio attribute in the export () method to avoid errors. However, you may want to be more restrictive and require that the Dictionaryio object be passed to the constructor, ensuring that the $dictio is always populated.

Call override Method

In Listing 3, Xmldictionaryio integrates Dictionaryio. While Dictionaryio writes and reads serialized data, Xmldictionaryio operates XML that can be shared with third-party applications. Xmldictionaryio can overwrite its parent method (import () and export ()), or it can choose not to provide its own implementation (path ()). If the client invokes the path () method in the Xmldictionaryio object, the path () method implemented in Dictionaryio is called.

In fact, both of these methods can be used at the same time. You can override the method and call the parent implementation. To do this, use the New keyword parent. Use the scope resolution operator and the name of the method being discussed to work with the parent. For example, suppose you need Xmldictionaryio to use a directory called XML 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 using an XML directory or a 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::p Ath ($dictionary, $ext);
}
// ...

As you can see, the method examines the local XML directory. If the test fails, it is assigned to the parent method using the parent keyword.

This news a total of 3 pages, currently on the 1th page 1 2 3


The

Subclass and constructor method

Parent keyword is especially important in constructor methods. If a constructor is not defined in a subclass, the parent constructor represents an explicit invocation of you. If you do not create a constructor method in the child class. It is your responsibility to call the constructor of the parent class and pass any arguments, as shown in Listing 4:

Listing 4. Invoking the parent class ' s constructor

Class Specialdictionary extends Dictionary {
function __construct ($t Ype, Dictionaryio $dictio, $additional) {
//do something with $additional
Parent::__construct ($type, $dicti O);
}
}


Abstract classes and methods

Although it is perfectly legal to provide the default behavior in the parent class, this may not be the most ingenious method. For starters, you must rely on the authors of the subclasses to understand that they must implement import () and export () to create a class in the broken state. Moreover, the Dictionaryio class is actually a brother, not a father and son. Xmldictionaryio is not a special case of dictionaryio; instead, it is an alternative implementation. The

PHP V5 allows you to define a partially implemented class whose primary role is to specify the core interface for its children. This class must be declared abstract.


Abstract class Dictionaryio {}


Abstract class cannot be instantiated. You must create a subclass (that is, create a class that inherits it) and create an instance of the subclass. You can declare standard and abstract methods in an abstract class, as shown in Listing 5. Abstract method

http://www.bkjia.com/PHPjc/532425.html www.bkjia.com true http://www.bkjia.com/PHPjc/532425.html techarticle Advanced PHPV5 Object Research This article describes some of the more advanced design-oriented features of PHPV5. These include various object types, which allow components in the system to be detached from one another, creating reusable ...

  • Related Article

    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.