PHP,区分内部和外部类方法调用

时间:2011-03-25 03:39:10

标签: php class methods

无法理解这一点,有没有办法检查方法是否在内部调用?我的意思是一个回溯来检查它是否被$ 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();

?>

也许这是可撤销的,但我真的需要它在我的大学项目?任何人都会遇到解决方案,或者知道如何确定解决方案。

感谢。

3 个答案:

答案 0 :(得分:1)

以下解决方案不起作用。


您可以使用debug_backtrace,但速度很慢。我真的建议你找到一种不同的方法来解决你想要克服的问题。

<?php
public function check() {
    $trace = debug_backtrace();
    if ($trace[1]['class'] == 'MyClassName') {
        return true;
    }
    return false;
}

答案 1 :(得分:0)

如果您有通话电话$ bar-&gt; callCheck();控制退出函数检查();

首先去 callCheck()然后在它之后检查()并从那里返回

答案 2 :(得分:0)

debug_backtrace();应该管用。放置debug_backtrace();在check()方法中。

这样做:

$ t = debug_backtrace(); 的var_dump($吨);

从这里你应该检查$ 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) {
    }
  }
}
相关问题