[英]PHP, distinguish between internal and external class method call
我無法解決這個問題,是否有任何方法可以檢查內部是否調用了方法? 我的意思是回溯,以檢查它是否被$ this調用,而不是實例的指針。 有點像私有功能的概念,但只有功能是公共的?
<?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();
?>
也許這是可以撤消的,但是我在大學的項目中確實需要它嗎? 任何人遇到解決方案或知道我將如何確定解決方案。
謝謝。
以下解決方案不起作用。
您可以使用debug_backtrace,但是會很慢。 我真的建議您找到另一種方法來解決您要克服的問題。
<?php
public function check() {
$trace = debug_backtrace();
if ($trace[1]['class'] == 'MyClassName') {
return true;
}
return false;
}
如果有電話,則$ bar-> callCheck(); 控制從函數check()退出;
首先去callCheck()然后再去check()然后從那里返回
debug_backtrace(); 應該管用。 放置debug_backtrace(); 內部check()方法。
做這個:
$ t = debug_backtrace(); var_dump($ t);
從這里,您應該檢查$ t ['function']和$ t ['class'],將這2結合起來,您應該發現是外部調用還是內部調用。
這是從我的機器上放出來的,php版本是5.2.14。
array(1) {
[0]=>
array(7) {
["file"]=>
string(15) "C:\php\test.php"
["line"]=>
int(24)
["function"]=>
string(5) "check"
["class"]=>
string(3) "Foo"
["object"]=>
object(Foo)#1 (0) {
}
["type"]=>
string(2) "->"
["args"]=>
array(0) {
}
}
}
array(2) {
[0]=>
array(7) {
["file"]=>
string(15) "C:\php\test.php"
["line"]=>
int(18)
["function"]=>
string(5) "check"
["class"]=>
string(3) "Foo"
["object"]=>
object(Foo)#1 (0) {
}
["type"]=>
string(2) "->"
["args"]=>
array(0) {
}
}
[1]=>
array(7) {
["file"]=>
string(15) "C:\php\test.php"
["line"]=>
int(26)
["function"]=>
string(9) "callCheck"
["class"]=>
string(3) "Foo"
["object"]=>
object(Foo)#1 (0) {
}
["type"]=>
string(2) "->"
["args"]=>
array(0) {
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.