Detailed explanation of Traits usage in PHP

PHP is a single-inheritance language, and before the advent of PHP 5.4 Traits, PHP classes could not inherit properties or methods from two base classes at the same time. The combined function of php's Traits and Go language is somewhat similar,

By using the use keyword in the class to declare the name of the Trait to be combined, and the declaration of a specific Trait uses the trait keyword, the Trait cannot be instantiated directly. Please see the following code for specific usage:

<?php
Drive trait {
    public $carName = 'BMW';
    public function driving() {
        echo "driving {$this->carName}\n";
    }
}
class Person {
    public function age() {
        echo "i am 18 years old\n";
    }
}
class Student extends Person {
    use Drive;
    public function study() {
        echo "Learn to drive \n";
    }
}
$student = new Student();
$student->study();
$student->age();
$student->driving();
Learn to drive
i am 18 years old
driving BMW

In the above example, the Student class inherits Person, has the age method, and by combining Drive, has the driving method and the property carName.

If there is a property or method with the same name in the Trait, the base class and this class, which one will be retained in the end? Test it with the following code: To be continued

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325108850&siteId=291194637