如何防止在 PHP 中使用超出“使用”范围的特征方法

2024-05-20

我想知道是否有任何方法可以防止在 PHP 的任何类上下文之外使用特征方法?

让我用一个简短的例子来解释我想要什么,这是我当前的代码:

// 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

关于traits的PHP手册页非常全面,并且处理了很多情况,但没有这个(http://php.net/manual/en/language.oop5.traits.php http://php.net/manual/en/language.oop5.traits.php)

我拼命地尝试删除“静态”并使用“公共”、“受保护”、“私有”,但当然,它就是行不通。到目前为止我没有其他想法,所以也许我错过了一些东西,或者这是不可能的?


使用特征时使用可见性改变功能:

trait MyFunctions {

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

}

class A {

    use MyFunctions { _hello_world as public hello_world ;}
    ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何防止在 PHP 中使用超出“使用”范围的特征方法 的相关文章

随机推荐