如何防止在“使用"之外使用 trait 方法?PHP 中的作用域 [英] How to prevent use of trait methods out of "use" scope in PHP

查看:26
本文介绍了如何防止在“使用"之外使用 trait 方法?PHP 中的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

PHP manual page about traits is very comprehensive, and a lot of cases are treated, but not this one (http://php.net/manual/en/language.oop5.traits.php)

我拼命地尝试删除静态"并使用公共"、受保护"、私有",但当然,它只是不起作用.到目前为止,我没有其他想法,所以也许我遗漏了什么,或者根本不可能?

I desperatly tried to remove "static" and use "public", "protected", "private", but of course, it just didn't work. I've no other ideas so far, so maybe I'm missing something, or it's just impossible ?

推荐答案

在使用 trait 时使用可见性更改功能:

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 ;}
    ...
}

这篇关于如何防止在“使用"之外使用 trait 方法?PHP 中的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆