Alexander  Pravdin
Alexander Pravdin

Reputation: 5569

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?

Upvotes: 4

Views: 9002

Answers (2)

WizKid
WizKid

Reputation: 4908

Change it to:

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

trait mixin {
    abstract function method();

    function mixinFunction() {
        $this->method();
    }
}

class currentClass extends baseClass {
    use mixin;

    function method() {
        $this->mixinFunction();
    }
}

Upvotes: 2

ZhukV
ZhukV

Reputation: 3178

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();

Upvotes: 2

Related Questions