What is a trait? Application scenarios of php traits

不言
Release: 2023-04-03 22:44:01
Original
1823 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template