10

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.

3
  • 4
    see conflict resolution php.net/manual/en/language.oop5.traits.php Commented Dec 11, 2012 at 22:35
  • Psst, you're trying to call a non-static method in a static way. You should be seeing a warning about that. Maybe you should turn your error_reporting level up. Commented Dec 11, 2012 at 22:38
  • Oh, oops, I forgot to add the static keywords in the description. They are both static in reality. – @rambocoder: Thanks, see edit. It did the trick. Commented Dec 11, 2012 at 22:39

2 Answers 2

11

You can do something like this:

class Bar{

    use Foo {
        Foo::foo as foofoo;
    }

    private static function foo(){

        self::foofoo();

        echo ' World!';

    }

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

2 Comments

Yep, exactly, except for the semicolon position and the static keyword ;) Thanks.
Yes, didn't see the change in the question to static.
0

Are you allowed to rename your trait method foo to fooo?

If yes, please do and replace Foo::foo() with Foo:fooo() in your class method body before following static call syntax (by adding static keyword to your trait function definition)

<?php

trait Foo 
{
    protected static function Fooo()
    {
        echo 'Hello';
    }
}

class Bar 
{
    use Foo;

    private static function foo() 
    {
        self::fooo();

        echo ' World!';
    }

    public static function expose() 
    {
        echo self::foo();
    }
}

echo Bar::expose();

EDIT:

Obviously, the answer to my question was "No, you're not allowed to rename the trait method", for which case, you've pointed out a solution related to native conflict resolution embedded in PHP: http://php.net/manual/en/language.oop5.traits.php#language.oop5.traits.conflict

Comments

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.