dbu
dbu

Reputation: 1562

PHP trait exposing a method and interfaces

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.

Upvotes: 2

Views: 291

Answers (1)

arbogastes
arbogastes

Reputation: 1328

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.

Upvotes: 2

Related Questions