PHP5:限制对某些类的函数的访问
PHP5中有没有办法只允许某个类或一组类调用特定的函数?例如,假设我有三个类(“Foo”、“Bar”和“Baz”),它们都具有类似名称的方法,并且我希望 Bar 能够调用 Foo::foo()< /code> 但拒绝 Baz 进行该调用的能力:
class Foo {
static function foo() { print "foo"; }
}
class Bar {
static function bar() { Foo::foo(); print "bar"; } // Should work
}
class Baz {
static function baz() { Foo::foo; print "baz"; } // Should fail
}
Foo::foo(); // Should also fail
Foo、Bar 和 Baz 之间不一定有继承,因此使用 protected
或类似的修饰符不会有帮助;但是,这些方法不一定是静态的(为了示例的简单性,我在这里将它们设置为静态)。
Is there a way in PHP5 to only allow a certain class or set of classes to call a particular function? For example, let's say I have three classes ("Foo", "Bar", and "Baz"), all with similarly-named methods, and I want Bar to be able to call Foo::foo()
but deny Baz the ability to make that call:
class Foo {
static function foo() { print "foo"; }
}
class Bar {
static function bar() { Foo::foo(); print "bar"; } // Should work
}
class Baz {
static function baz() { Foo::foo; print "baz"; } // Should fail
}
Foo::foo(); // Should also fail
There's not necessarily inheritance between Foo, Bar, and Baz, so the use of protected
or similar modifiers won't help; however, the methods aren't necessarily static (I made them so here for the simplicity of the example).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有语言功能可以给你这种行为,听起来你想模仿 C++ 友元类之类的东西?
但是,在 foo() 方法中,您可以使用 debug_backtrace 来查找你的调用者是谁,如果它不想要你想要的,就抛出异常!
There's no language feature which could give you that behaviour, sounds like you want to emulate something like C++ friend classes?
However, inside the foo() method you could use debug_backtrace to find out who your caller was, and throw an exception if its not want you want!
我创建了一个函数来执行此操作,这可能会有所帮助。
I've create a function for doing this that might be helpful.
有点捏造,但如果您想要一个更简单、内存占用更少的替代方案来使用 debug_backtrace(),您可能需要该方法的一个附加参数,该参数必须是某些特定的秘密 /em> 值。例如:-
这并不能阻止某人查看代码并解决它,但是通过异常中的合理消息,您应该能够传达您打算如何使用这些类。
您甚至可以更进一步,使用 php 的魔法
__call 实现与 C++ 的 friend 类 非常相似的东西()
和__callStatic()
方法,这意味着您可以在不污染实际方法的情况下进行秘密检查。这样做的缺点是您不会获得这些方法的 IDE 提示,因为您需要为它们添加前缀或其他内容,否则魔术方法将被绕过。A bit of a fudge, but if you wanted a simpler less memory intensive alternative to using
debug_backtrace()
you could require an additional argument to the method that would have to be of some specific secret value. So for example:-This doesn't stop someone looking through the code and working around it, however with a sensible message in the exception you should be able to convey how you intended the classes to be used.
You could even go further and implement something very similar to C++'s friend classes using php's magic
__call()
and__callStatic()
methods, this would mean you could do the secret checking without polluting the actual methods. The disadvantage of this would be you wouldn't get the IDE hinting for those methods because you would need to prefix them or something, otherwise the magic methods are bypassed.