[Modern PHP] Chapter II new features of the three Traits

Source: Internet
Author: User
Tags php language traits
Traits

Many of my PHP developer friends are not familiar with traits, which is a new concept introduced in PHP 5.4.0. Traits looks like an interface but uses it like a class, what exactly is it? Neither of them is.

A trait has partial implementations (such as constants, properties, and methods) that can be implanted into one or more actual PHP classes. Trait has two responsibilities: indicates what a class can do (like interfaces); Provides a modular implementation (similar to a class).

In other languages you may have a certain understanding of traits. Ruby's modules and mixins functions, for example, are similar to PHP's traits.

Why do we use traits

The PHP language uses a classic inheritance model. This means that you start with a generic root class that provides a basic implementation. Create more specific classes from the root class, which directly inherit the various implementations of the parent class. This is called an inheritance hierarchy, and many programming languages use this common pattern.

For ease of understanding, suppose you go back to high school to study biology. Do you remember the genus of the organisms you studied? A total of six major sectors, bounded by the derivation out, the door derived from the outline, the main derivative of the interns, the derivative of the branch derived from genus, belong to the following species. Each downward derivation at the level of a species represents a specific trait.

The classic inheritance model works well in most cases. But what if there are two unrelated classes that need to implement similar behavior? For example, a PHP class called Retailstore, and another PHP class called car, they can be said to be completely unrelated to the two classes, on the inheritance relationship simply cannot share a common parent class. However, two classes need to use latitude and longitude in a geographic location to display map coordinates.

We have created traits to solve this problem. They can inject part of the implementation into irrelevant classes. Traits also facilitates the reuse of code.

Encountering this problem, my first solution (and worst of all) is to create a common parent class geocodable used to inherit from the two classes of Retailstore and car. This solution is too bad, because forcing two unrelated classes to share a common ancestor is particularly awkward at their respective inheritance levels.

My second solution (slightly better) is to create a geocodable interface that defines which methods are required to implement a geographic location. Retialstore and car Two classes can implement this geocodable interface. It is really a good solution to have each class retain its own natural inheritance relationship. But we still need to repeat the definition of the interface in each class, which is not a dry solution.

Dry is the abbreviation for do not repeat yourself. As a good programming habit, we should never repeat the same code in multiple places. Cannot appear because the change of a code, and the passive also to modify the same code elsewhere in the case.

My third scenario (the best solution) is to construct a geocodable trait that defines and implements the relevant methods. I can add geocodable trait to the Retailstore class and car class without disrupting the class's inheritance hierarchy.

How to construct a trait

The following shows how to define a PHP trait:

 
as a good habit, we should make a file a trait, just like the definition of a class and an interface.

Let's go back to our geocodable example to better demonstrate the use of trait. We all know that the Retailstore and car classes need to support geolocation capabilities, and we can all agree that inheritance and interfaces are not the best solution. Instead, we construct a geocodable trait to return a longitude and latitude coordinate that can be marked on the map. Example 2-12 is our complete geocodable trait.

Example 2-12 definition of geocodable trait

   Geocoder = $geocoder;    The Public Function setaddress ($address) {$this->address = $address; Public Function Getlatitude () {if (Isset ($this->geocoderresult) = = = False) {$this->geoco        Deaddress ();    } return $this->geocoderresult->getlatitude (); Public Function Getlongitude () {if (Isset ($this->geocoderresult) = = = False) {$this->GEOC        Odeaddress ();    } return $this->geocoderresult->getlongitude (); } protected function geocodeaddress () {$this->geocoderresult = $this->geocoder->geocode ($this->a        ddress);    return true; }}

Geocodable trait only defines the properties and methods required to implement Geolocation functionality without any additional functionality.

Our geocodable trait defines the properties of three classes:

To be Continued ...

The above describes the [modern PHP] the second chapter of the new features of the three Traits, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • 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.