know-how.dev

How to override trait method and call it from the overridden one in PHP?

3 years ago 947

For example, you have a trait with public method increment and some class using it:

trait SomeTrait {
    public function increment(int $value): int
    {
        return ++$value;
    }
}

class SomeClass {
    use SomeTrait;
}

$some = new SomeClass();

var_dump($some->increment(1));

// int(2)

And you want to add some changes to this method. You can try to override it and use parent:: structure like this:

class SomeClass {
    use SomeTrait;

    public function increment(int $value): int
    {
        if ($value === 2) {
            return 0;
        }

        return parent::increment($value);
    }
}

$some = new SomeClass();

var_dump($some->increment(1));

But it will fail with error like Cannot access parent:: when current class scope has no parent. That's because traits are not classes, their behavior is different. To make it work you can use the next workaround:

class SomeClass {
    use SomeTrait {
        increment as incrementParent;
    }

    public function increment(int $value): int
    {
        if ($value === 2) {
            return 0;
        }

        return $this->incrementParent($value);
    }
}

$some = new SomeClass();

var_dump($some->increment(1));

// int(2)