PHP insteadof Keyword

PHP interface Keyword
PHP instanceof Keyword

In this article, you will learn how to select the trait method to execute in PHP. The insteadof keyword in PHP allows you to select from which trait a method should be taken if more than one trait has a method with the same name.

examples of the INSTEADOF function

Example 1. In this example, we use insteadof to choose methods from different traits.

<?php
trait message1 {
  public function msgA() {
    echo "My favorite color is red. ";
  }

  public function msgB() {
    echo "My favorite number is 5. ";
  }
}

trait message2 {
  public function msgA() {
    echo "My favorite color is blue. ";
  }

  public function msgB() {
    echo "My favorite number is 7. ";
  }
}

class MyClass {
  use message1, message2 {
    message1::msgA insteadof message2;
    message2::msgB insteadof message1;
  }
}

$obj = new MyClass();
$obj->msgA();
$obj->msgB();
?>
PHP interface Keyword
PHP instanceof Keyword
en English
X
Scroll to Top