Home Backend Development PHP Tutorial [Modern PHP] Chapter 2 New Features Three Traits

[Modern PHP] Chapter 2 New Features Three Traits

Jul 30, 2016 pm 01:31 PM
this trait

Traits

Many of my PHP developer friends don’t know much about traits, which is a new concept introduced in PHP 5.4.0. Traits look like interfaces but work like classes, so what exactly are they? It's neither.

A trait has partial implementation (such as constants, properties and methods) that can be embedded into one or more actual PHP classes. Traits have two responsibilities: indicating what a class can do (similar to an interface); and providing a modular implementation (similar to a class).

You may already have some understanding of traits in other languages. For example, the functions of Ruby's modules and mixins are very similar to PHP's traits.

Why should we use traits

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

To make it easier to understand, imagine that you travel back in time to high school to study biology. Do you still remember the phylum, order, family, genus and species of the organisms you studied? There are six major realms in total. The realm is derived from the door, the phylum is derived from the class, the class is derived from the order, the order is derived from the family, the family is derived from the genus, and the genus is followed by the species. Each descent down the species hierarchy represents a specific characteristic.

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, one PHP class is called RetailStore, and another PHP class is called Car. They can be said to be two completely unrelated classes, and they cannot share a common parent class in terms of inheritance relationship. However, both classes require the longitude and latitude from the geographic location to display map coordinates.

We created traits to solve this problem. They can inject partial implementation into unrelated classes. Traits also facilitate code reuse.

When I encounter this problem, my first solution (and the worst) is to create a public parent class Geocodable for the RetailStore and Car classes to inherit. This solution is really bad, because forcing two unrelated classes to share a common ancestor looks very awkward in their respective inheritance hierarchies.

My second solution (slightly better) is to create a Geocodable interface that defines what methods are needed to implement geolocation. Both RetialStore and Car classes can implement this Geocodable interface. It is indeed a good solution to allow each class to retain its natural inheritance relationship. But we still need to repeat the definition in the interface in each class, which is not a DRY solution.

DRY is the abbreviation of Do not repeat yourself. As a good programming practice, we should never repeat the same code in multiple places. There cannot be a situation where you have to passively modify the same code in other places because you have changed one piece of code.

My third solution (the best solution) is to construct a Geocodable trait and define and implement related methods in it. I can add Geocodable traits to the RetailStore class and Car class without disrupting the class inheritance hierarchy.

How to construct a trait

The following shows how to define a PHP trait:

<?php
trait MyTrait {
    // 此处是trait的具体实现
}
Copy after login

As a good habit, we should do one trait per file, just like the definition of classes and interfaces .

Let’s go back to our Geocodable example to better demonstrate the use of traits. We all know that the RetailStore class and the Car class need to support the geographical positioning function, and we can all agree that inheritance and interfaces are not the best solution. Instead, we construct a Geocodable trait that returns a longitude and latitude coordinate that can be marked on the map. Example 2-12 shows our complete Geocodable trait.

Example 2-12 Definition of Geocodable trait

<span style="font-size:14px;"><?php
trait Geocodable {
    /** @var string */
    protected $address;

    /** @var \Geocoder\Geocoder */
    protected $geocoder;

    /** @var \Geocoder\Result\Geocoded */
    protected $geocoderResult;

    public function setGeocoder(\Geocoder\GeocoderInterface $geocoder)
    {
        $this->geocoder = $geocoder;
    }

    public function setAddress($address)
    {
        $this->address = $address;
    }

    public function getLatitude()
    {
        if (isset($this->geocoderResult) === false) {
            $this->geocodeAddress();
        }

        return $this->geocoderResult->getLatitude();
    }

    public function getLongitude()
    {
        if (isset($this->geocoderResult) === false) {
            $this->geocodeAddress();
        }

        return $this->geocoderResult->getLongitude();
    }

    protected function geocodeAddress()
    {
        $this->geocoderResult = $this->geocoder->geocode($this->address);

        return true;
    }
}</span>
Copy after login

Geocodable trait only defines the properties and methods required to implement the geographical location function without any additional functions.

Our Geocodable trait defines properties of three classes:

To be continued...

The above introduces [Modern PHP] Chapter 2 New Features Three Traits, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP trait DTO: Simplifying the development of data transfer objects PHP trait DTO: Simplifying the development of data transfer objects Oct 12, 2023 am 09:04 AM

PHPtraitDTO: Simplifying the development of data transfer objects Introduction: In modern software development, data transfer objects (DataTransferObject, referred to as DTO) play an important role. DTO is a pure data container used to transfer data between layers. However, during the development process, developers need to write a large amount of similar code to define and operate DTOs. In order to simplify this process, the trait feature was introduced in PHP. We can use the trait feature to

In-depth understanding of the design patterns and practices of PHP trait DTO In-depth understanding of the design patterns and practices of PHP trait DTO Oct 12, 2023 am 08:48 AM

In-depth understanding of the design patterns and practices of PHPtraitDTO Introduction: In PHP development, design patterns are an essential part. Among them, DTO (DataTransferObject) is a commonly used design pattern used to encapsulate data transfer objects. In the process of implementing DTO, using traits can effectively improve the reusability and flexibility of the code. This article will delve into the design patterns and practices of traitDTO in PHP

PHP trait DTO: a key tool for optimizing the data transfer process PHP trait DTO: a key tool for optimizing the data transfer process Oct 12, 2023 pm 03:10 PM

PHPtraitDTO: A key tool for optimizing the data transmission process. Specific code examples are required. Introduction: During the development process, data transmission is a very common requirement, especially when data is transferred between different levels. In the process of transmitting this data, we often need to process, verify or convert the data to meet different business needs. In order to improve the readability and maintainability of the code, we can use PHPtraitDTO (DataTransferObject) to optimize

PHP trait DTO: achieving simplicity and flexibility in data transfer objects PHP trait DTO: achieving simplicity and flexibility in data transfer objects Oct 12, 2023 am 10:21 AM

PHPtraitDTO: Implementing simplicity and flexibility of data transfer objects Introduction: In the PHP development process, data transmission and processing are often involved. The DataTransferObject (DTO for short) is a design pattern that is used to transfer data between different layers. During the transmission process, DTO simplifies data operations by encapsulating data and providing public access methods. This article will introduce how to use PHPtrait to implement DT

Implement a highly customizable data transfer framework using PHP trait DTO Implement a highly customizable data transfer framework using PHP trait DTO Oct 12, 2023 pm 12:46 PM

Implementing a highly customizable data transfer framework using PHPtraitDTO As websites and applications become more complex, data transfer becomes more and more important. In PHP, using DataTransferObject (DTO for short) to handle data transfer can greatly simplify the code and improve maintainability and scalability. This article will introduce how to use PHPtrait and DTO to implement a highly customizable data transfer framework and provide corresponding code examples.

PHP trait DTO: elegant data transfer object pattern PHP trait DTO: elegant data transfer object pattern Oct 12, 2023 am 08:34 AM

PHPtraitDTO: Elegant Data Transfer Object Pattern Overview: Data Transfer Object (DTO for short) is a design pattern used to transfer data between different layers. In applications, it is often necessary to obtain data from a database or external service and pass it between different layers of the application. The DTO mode can make data transmission more concise and clear, and also facilitates expansion and maintenance. In PHP, we can use traits to implement DTO

PHP trait DTO: a key tool for optimizing the data transfer process PHP trait DTO: a key tool for optimizing the data transfer process Oct 12, 2023 am 09:27 AM

PHPtraitDTO: A key tool for optimizing the data transmission process. Specific code examples are required. In the development process, data transmission is a very critical link. How to transmit data efficiently has become one of the problems that developers need to solve. In PHP language, using traitDTO (DataTransferObject) can optimize the data transmission process and improve the efficiency of data transmission. This article will introduce what traitDTO is and how to use it to optimize the data transfer flow

An article that understands this point and catches up with 70% of front-end people An article that understands this point and catches up with 70% of front-end people Sep 06, 2022 pm 05:03 PM

A colleague got stuck due to a bug pointed by this. Vue2’s this pointing problem caused an arrow function to be used, resulting in the inability to get the corresponding props. He didn't know it when I introduced it to him, and then I deliberately looked at the front-end communication group. So far, at least 70% of front-end programmers still don't understand it. Today I will share with you this link. If everything is wrong If you haven’t learned it yet, please give me a big mouth.

See all articles