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; } }
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; //这是类的实现 }
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('420 9th Avenue, New York, NY 10001 USA');
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!

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment
