Understanding Php Traits Scope

时光怂恿深爱的人放手 提交于 2020-02-06 07:56:52

问题


I have The following files

1) A Class called Helper

    class Helper
    {
        public static function a(){
            //
        }
    }

2) A Trait called SpecialTrait

    Trait SpecialTrait
    {
        public function b(){
            Helper::a();
        }
    }

3) A Controller Class Extending Controller called UserController

    use path\to\Helper;
    use path\to\SpecialTrait

    class UserController extends Controller
    {
        use SpecialTrait;

        public function c(){
            $this->b();
        }
    }

When the program runs and function c() is called which is meant to call a trait function b() which uses a helper class static function a()

This fails to work, the only fix being to also use the helper class in the traits file.

    use path\to\Helper;

    Trait SpecialTrait
    {
        public function b(){
            Helper::a();
        }
    }

My question is that according to my understanding of traits, the traits functions are copied and pasted in during run time and if that were the case wouldn't the trait function b() be able to see or have the helper class within its scope rather than requiring it to be imported/used in its own file.

来源:https://stackoverflow.com/questions/59732901/understanding-php-traits-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!