PHP,区分内部和外部类方法调用 [英] PHP, distinguish between internal and external class method call
问题描述
不能让我的头,这是,有什么方法来检查一个方法是否在内部调用?我的意思是一个回溯,检查它是否被$ this调用,而不是一个指向实例的指针。类似私人功能的概念,但只有功能是公共的?
Can't get my head around this, is there any way to check if a method was called internally? By this I mean a traceback to check if it was called by $this and not a pointer to the instance. Kind of like the concept of private function but only function is public?
<?php
class Foo {
public function check () {
/*
if invoked by $this (internally)
return true
else
return false
*/
}
public function callCheck () {
/* returns true because its called by $this */
return $this->check();
}
}
$bar = new Foo;
// this should return false because we are calling it from an instance
$bar->check();
// where as this will return true
$bar->callCheck();
?>
也许这是可撤销的,但是我真的需要它在我的大学项目吗?任何人遇到解决方案或知道如何识别解决方案。
Maybe this is undo-able but I really need it for my project at university? Anyone come across a solution or knows how I would identify a solution.
谢谢。
推荐答案
以下解决方案无效。
您可以使用 debug_backtrace 但它会很慢。我真的建议你找到一个不同的方法来解决你想克服的问题。
You could use debug_backtrace but it will be slow. I really advise you find a different way to solve the problem you are trying to overcome.
<?php
public function check() {
$trace = debug_backtrace();
if ($trace[1]['class'] == 'MyClassName') {
return true;
}
return false;
}
这篇关于PHP,区分内部和外部类方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!