gpt4 book ai didi

php - 如何防止在 PHP 中使用超出 "use"范围的特征方法

转载 作者:可可西里 更新时间:2023-11-01 00:20:45 25 4
gpt4 key购买 nike

我想知道是否有任何方法可以防止在 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 )

我拼命地尝试删除“static”并使用“public”、“protected”、“private”,但是当然,它就是行不通。到目前为止我没有其他想法,所以也许我遗漏了什么,或者这根本不可能?

最佳答案

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

trait MyFunctions {

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

}

class A {

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

关于php - 如何防止在 PHP 中使用超出 "use"范围的特征方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25103688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com