Table of Contents
For example
Home Backend Development PHP Tutorial What is a trait? Application scenarios of php traits

What is a trait? Application scenarios of php traits

Aug 29, 2018 pm 03:29 PM

The content of this article is about what are traits? The application scenarios of PHP traits have certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Why use traits?

The PHP language uses a typical inheritance model. In this model, we first write a general root class to implement basic functions, and then extend this root class to create a more specific class that inherits the implementation from the direct parent class. This is called an inheritance hierarchy, and many programming languages ​​use this pattern.

Most of the time, this typical inheritance model works well. However, what should you do if you want two unrelated PHP classes to have similar behavior? For example, the two PHP classes RetailStore and Car have very different functions and have no common parent class in the inheritance hierarchy. However, both classes should be able to use geocoding techniques to convert to latitude and longitude and then display them on the map.
Traits were born to solve this problem. Traits can be used to implement modular implementations into multiple unrelated classes. And traits can also promote code reuse.
In order to solve this problem, my first reaction was to create a parent class Geocodable (this is not good) and let both Retalstore and Car inherit this class. This solution is bad because we force two unrelated classes to inherit from the same ancestor, and it's obvious that this ancestor does not belong to their respective inheritance hierarchies.
My final reaction was to create the Geocodable trait (which is the best way to do it), define and implement the Geocodable class method, and then mix this trait into the Retailstore and Car classes. Doing so will not disturb the natural inheritance hierarchy.

For example

We hope that the RetailStore and Car classes provide geocoding functionality, and realize that inheritance and interfaces are not the best solution. The solution we chose was to create a Geocodable trait, return the latitude and longitude, and then plot it in a map. The definition of Geocedable traits is as follows:

?php
trait Geocodable {
	/** @var string */
	protected $address;

	/** @var \Geocoder\Geocoder */
	protected $geocoder;
	/** @var \GeocoderlResult\Geocoded */
	protected $geocoderResult;
	public function setGeocoder(\Geocoder\GeocoderIntertace $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;
	}
}
Copy after login

Geocodable traits only need to define the attributes and methods required to implement the geocoding function, and nothing else is needed. This Geocodable trait defines three class attributes: one represents Address (string), one is the geocoder object, and the other is the result object obtained after geocoder processing. We also define four public methods and one protected method. The setGeocoder() method is used to inject the Geocoder object; the setAddress() method is used to set the address; the getlatitude() and getLongitude() methods return the latitude and longitude respectively; the geocodeAddress() method passes the address string to the Geocoder instance to obtain the longitude The result obtained by the encoder processing.
How to use traits?

The method of using PHP traits is very simple, just add the use MyTrait; statement to the definition body of the PHP class. Here's an example. Obviously, MyTrait must be replaced with the corresponding PHP trait name in actual use.

<?php
class MyClass{
    use MyTrait;
    //这是类的实现
}
Copy after login

Suggestion: Use the use keyword to import both namespaces and traits, but the import locations are different. Namespaces, classes, interfaces, functions, and constants are imported outside the class definition, and traits are imported inside the class definition. The difference is small, but important. And the prerequisite for using use is that you have included the PHP file.

We only have to do so much. Now, every Retailstore instance can use the properties and methods provided by the Geocodable trait, that is:

$store = new RetailStore();
$store->setddress(&#39;420 9th Avenue, New York, NY 10001 USA&#39;);
Copy after login

The php interpreter will copy and paste the trait into the class definition body at compile time.

Related recommendations:

Detailed explanation of PHP namespaces, traits and generators

The above is the detailed content of What is a trait? Application scenarios of php traits. For more information, please follow other related articles on the PHP Chinese website!

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles