Back to questions
JuniorTheoryCommon
What does the program print?
<?php
trait Greets
{
public function hello(): string { return 'trait'; }
}
class App
{
use Greets;
public function hello(): string { return 'class'; }
}
echo (new App())->hello(), "\n";class
- Expecting the trait's
hello()to replace the class's own: a method declared in the class itself always wins over a trait method of the same name. - Expecting a fatal error for the shared name: a class method beside a trait method is allowed; only two traits that bring one method name collide and need
insteadof.
- Which
hello()runs ifAppdrops its own method but its parent class has one? - How do you choose a method when two traits bring the same name?