2

I have a base class with a protected method, a trait that makes that method public and an interface that requires that method as public. Boiled down example is this:

<?php

class b
{
    protected function method() {echo 'base';}
}

trait t
{
    public function method()
    {
        parent::method();
    }
}

interface e
{
    public function method();
}

class c extends b implements e
{
    use t;
}

$c = new c();
$c->method();

This gives me a fatal error:

Fatal error: Access level to b::method() must be public (as in class e)

(it says class and not interface e, but whatever).

I tried to be explicit with use t {method as public;} but that makes no difference.

If i comment out the implements e bit from class c, i do see "base" printed on the console.

My PHP version is 5.5.9-1ubuntu4.11.

1 Answer 1

2

It's true that Traits have high precedence and Trait methods override inherited methods. But forget about Trait in your example. This error is all because of interface e and class b. When you are using interface then you are defining a contract with an interface. All methods declared in an interface must be public; this is the nature of an interface. - as the PHP documentation says and with protected function method() in class b you are breaking the contract.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for replying. Yes that would be the whole point of the thing, my trait should (among other things of course) make one protected method public. As the method in class c is technically public, i would expect the interface to see that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.