[TRAIT] Ưu tiên phương thức trong traits (ok)

https://toidicode.com/traits-trong-php-108.html

C:\xampp\htdocs\php\b.php

<?php
//trait SetGetName
trait SetGetName {
  public function setName($name) {
    $this->name = $name;
  }
  public function getName() {
    return $this->name;
  }
  public function getAll() {
    return $this->getName();
  }
}
//trait SetGetAge
trait SetGetAge {
  public function setAge($age) {
    $this->age = $age;
  }
  public function getAge() {
    return $this->age;
  }
  public function getAll() {
    return $this->getAge();
  }
}
class ConNguoi {
  private $name;
  private $age;
  //gọi trait
  use SetGetName, SetGetAge {
    //ưu tiên sử dụng phương thức getall của trait SetGetAge
    SetGetAge::getAll insteadof SetGetName;
  }
}
$connguoi = new ConNguoi();
$connguoi->setAge(22);
echo $connguoi->getAll();

Last updated