Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Method Collision

A method collision happens when a trait is imported in a class, and it holds a method that already exists in the class.

To solve such a collision, the code must use insteadof and use keywords, in the use expression.

There is no collision between the imported trait and the parent of the class, as the trait has priority over the parent. There is also no collision when a trait imports another trait: the last method has precedence.

<?php

    trait Herd {
        function trumpet() { echo __METHOD__; }
    }

    trait Waterhole {
        function trumpet() { echo __METHOD__; }
    }

    class Elephpant {
        use waterhole, herd {
            use herd::trumpet instead of waterhole;
        }
    }

    new elephpant()->stampede();

?>

Documentation

See Also