Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Trait call inherited function

I have got a trait

trait Foo{

    protected static function foo(){
        echo 'Hello';
    }
}

and a class

class Bar{
    use Foo;

    private static function foo(){
        Foo::foo();

        echo ' World!';
    }
}

I cannot use Foo:foo(). What can I do to achieve the desired effect?

EDIT

Using

use Foo {foo as parentFoo}

private static function foo(){

    self::parentFoo();

    echo ' World!';

}

did the trick.

like image 622
arik Avatar asked Dec 11 '12 22:12

arik


People also ask

Can traits be inherited PHP?

In PHP, a trait is a way to enable developers to reuse methods of independent classes that exist in different inheritance hierarchies. Simply put, traits allow you to create desirable methods in a class setting, using the trait keyword. You can then inherit this class through the use keyword.

How do you call a trait function?

Overriding a trait function Let's create a simple trait and use it in a class. Executing (new MyClass)->sayHi(); will output "trait says hi". The trait function can be overridden simply by defining a function with the same name in the class. Now (new MyClass)->sayHi(); will output "class says hi".

How do you call a trait in PHP?

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

Can a trait extend a class PHP?

Only classes can be extended. Traits are not classes.


1 Answers

You can do something like this:

class Bar{

    use Foo {
        Foo::foo as foofoo;
    }

    private static function foo(){

        self::foofoo();

        echo ' World!';

    }

}
like image 56
Mike Brant Avatar answered Sep 27 '22 17:09

Mike Brant