Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to indicate a parameter that "include trait" in PHPDoc

Recently I ran into an interesting situation when implementing a PHP application using PhpStorm. The following code snippet illustrates the problem.

    interface I{
        function foo();
    }

    trait T{
        /**
         * @return string
         */
        public function getTraitMsg()
        {
            return "I am a trait";
        }
    }

    class A implements I{
        use T;
        function foo(){}
    }

    class C implements I{
        use T;
        function foo(){}
    }

    class B {
        /**
         * @param I $input <===Is there anyway to specify that $input use T? 
         */
        public function doSomethingCool($input){ //An instance of "A" or "C"
           $msg = $input -> getTraitMsg();  //Phpstorm freaks out here
        }
    }

My question is in the comment. How do I indicate that $input parameter implements I and uses T?

like image 677
Wei Ma Avatar asked Jan 28 '26 05:01

Wei Ma


1 Answers

It's a lit bit hackly, but you can use class_uses it returns list of used traits. And add T as a @param type in PHPDoc for autocomplete

class B {
    /**
     * @param I|T $input <===Is there anyway to specify that $input use T?
     */
    public function doSomethingCool($input){ //An instance of "A" or "C"
        $uses = class_uses(get_class($input));
        if (!empty($uses['T'])) {
            echo $input->getTraitMsg();  //Phpstorm freaks out here
        }
    }
}
like image 90
Alex Kapustin Avatar answered Jan 30 '26 20:01

Alex Kapustin