Home>Article>Backend Development> What are PHP Traits

What are PHP Traits

藏色散人
藏色散人 Original
2019-01-19 15:26:27 4236browse

If you are a PHP newbie, or you are a senior PHP programmer, you may have heard of Traits, but some friends may not know what they do and why they are needed...

What are PHP Traits

Fortunately, Traits are much simpler than you think.

So, what are these so-called Traits?

Trait is a class containing methods. This Trait can be shared with many classes. All classes that use this trait can use trait methods.

Why might you want to use a Trait?

There may be many reasons why you might want to use a certain trait. For example, we have a function that needs to be used throughout the project. We can always create a global function or we can include this function (method) in a trait. And then anywhere we need to use this method, we can use this trait and that method will be available to us.

Look at the following traits:

trait Greeting{ public function sayHello($name){ return 'Hello ' . $name; }}

Now we can use this trait in any class:

class Post{ use Greeting;}class Page{ use Greeting;}

Since we have used this in the above two classes feature, now we can access the sayHello method in both instances: A class inherits, then you may wish to use

trait

.

The above is the detailed content of What are PHP Traits. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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