Php 如何限制公共函数仅由类/命名空间访问?
在为我的项目开发一个小型数据库包装器时,我想限制对函数的访问。Php 如何限制公共函数仅由类/命名空间访问?,php,class,namespaces,Php,Class,Namespaces,在为我的项目开发一个小型数据库包装器时,我想限制对函数的访问。 此限制应防止插件(位于不同的命名空间中,但能够通过设计访问此包装器)执行该功能 这怎么可能呢?我在这里回答我自己的问题。如果您还有其他建议,请随时改进 虽然PHPs内部无法直接限制这种形式的访问。功能可以“保护”自身。 这是通过利用\debug\u backtrace()获取有关调用方的信息并评估其命名空间和/或类来实现的 一个例子: /** * Will return true if called from within 'Na
此限制应防止插件(位于不同的命名空间中,但能够通过设计访问此包装器)执行该功能
这怎么可能呢?我在这里回答我自己的问题。如果您还有其他建议,请随时改进 虽然PHPs内部无法直接限制这种形式的访问。功能可以“保护”自身。
这是通过利用
\debug\u backtrace()
获取有关调用方的信息并评估其命名空间和/或类来实现的
一个例子:
/**
* Will return true if called from within 'Namespace\Class', false otherwhise.
*
* @return bool
*/
public function test() {
// Get debug_backtrace. This function will be at index 0.
$backtrace = \debug_backtrace();
// If the caller is a function it will be at index 1, if not, it will not exist
// and we will not execute the indented code.
if (false === \array_key_exists(1, $backtrace)
// If the caller is within a class the 'class' key will exist
|| false === \array_key_exists('class', $backtrace[1])
// and its name including namespace(s) will be the string-value of this key.
// If it does not exist nor start with 'Namespace\Class' this block will trigger.
|| 0 !== \strpos($backtrace[1]['class'], 'Namespace\Class')
) {
return false;
}
return true;
}
这是一个草率的解决方案,因为在不同的系统上,
debug\u backtrace
可能会给出不同的结果。例如,我在Debian上开发,但我的生产服务器在FreeBSD上。在这两个系统上,debug\u backtrace
有不同的输出,这导致您必须在Debian上工作,但最终失败,并且每次在FreeBSD上运行时都返回false。感谢您指出这一点。虽然我认为在不同的平台上不应该有所不同,但有必要指出这样的事实。谢谢