phpinheritancetraits

PHP: How to call parent method from a trait method used in current class?


Let we have following classes:

class baseClass {
    function method() {
        echo 'A';
    }
}

trait mixin {
    function mixinFunction() {
        ... /// <-- problem here
    }
}

class currentClass {
    use mixin;

    function method() {
        mixinFunction();
    }
}
...
$object = new currentClass();
$object->method();

Is it possible to execute baseClass::method() from trait to echo 'A' when calling $object->method(); without changing this class/method structure and without calling non-static method as static?


Solution

  • The all method from trait copy to class, and you must call to methods as -> or ::.

    trait mixin {
        function mixinFunction() {
            ... /// <-- problem here
        }
    }
    
    class currentClass {
        use mixin;
    
        function method() {
            $this->mixinFunction();
        }
    }
    ...
    $object = new currentClass();
    $object->method();