How to prevent using trait methods from "use" scope in PHP

I would like to know if there is a way to prevent trait methods from being used from any class context in PHP?

Let me explain what I want with a short example, here is my current code:

// File : MyFunctions.php
trait MyFunctions {

    function hello_world() {
        echo 'Hello World !';
    }

}

// File : A.php
include 'MyFunctions.php';

class A {

    use MyFunctions;

}

// File : testTraits.php
include 'A.php';

hello_world(); // Call to undefined function -> OK, expected
A::hello_world(); // Hello World ! -> OK, expected
MyFunctions::hello_world(); // Hello World ! -> Maybe OK, but not expected, I'd like to prevent it

      

The PHP man page on traits is very extensive and gets handled most of the time, but not this one ( http://php.net/manual/en/language.oop5.traits.php )

I tried desperately to remove the "static" ones and use "public", "protected", "private", but of course it just didn't work. I have no other ideas yet, so maybe I am missing something, or is it just not possible?

+3


source to share


2 answers


Use the function of changing the visibility when using the characteristic:



trait MyFunctions {

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

}

class A {

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

      

+5


source


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

If you really need to, you can dynamically work with this behavior by wrapping your function with a test that determines if there is a match between the magic constants __CLASS__

(name of the class in which the trait is used) and __TRAIT__

(name of the trait itself).

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



So your example would become:

trait MyFunctions {

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

}

      

+2


source







All Articles