PHP, distinguish between internal and external cla

2019-05-29 08:01发布

问题:

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.

Thanks.

回答1:

Below solution does not work.


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;
}


回答2:

if you there is a call $bar->callCheck(); control exits from function check();

first it go to callCheck() then after it goest to check() and return from there



回答3:

debug_backtrace(); should work. place the debug_backtrace(); inside check() method.

do this:

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

from here you should check $t['function'] and $t['class'], combine those 2 , you should find out is a call, external or internal.

here is out put from my machine, php version is 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) {
    }
  }
}