How to prevent use of trait methods out of “use” scope in PHP

放肆的年华 提交于 2019-12-03 17:27:57

Use the visibility changing feature when using a trait:

trait MyFunctions {

    private function _hello_world() {
        echo 'Hello World !';
    }

}

class A {

    use MyFunctions { _hello_world as public hello_world ;}
    ...
}

Using traits in PHP establishes the contract that functions defined in the trait can always be called as if they were defined as static methods.

If you really must, you can work around that behaviour dynamically by wrapping your function with a test that determines whether there is a match between magic constants __CLASS__ (the name of the class the trait is used in) and __TRAIT__ (the name of the trait itself).

If there is a match, then the method was not used as intended and you tweak its behaviour accordingly.

So your example would become:

trait MyFunctions {

    function hello_world() {
        if (__CLASS__ == __TRAIT__) {
            die('Sorry');
        }
        echo 'Hello World !';
    }

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