Last active
August 29, 2015 14:03
-
-
Save jk/0f4d4f216dea407b9631 to your computer and use it in GitHub Desktop.
Detect if a method call was from inside the class or outside
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Internal { | |
public function whosGonnaCall() { | |
$backtrace = debug_backtrace(); | |
assert(is_array($backtrace)); | |
assert(is_array($backtrace[1])); | |
assert(isset($backtrace[1]['class'])); | |
$callerClass = $backtrace[1]['class']; | |
$thisClassName = get_class($this); | |
assert($thisClassName == 'Internal'); | |
$callerIsSelf = false; | |
if ($thisClassName == $callerClass) { | |
$callerIsSelf = true; | |
} | |
$returnString = null; | |
if ($callerIsSelf) { | |
assert($callerIsSelf == true); | |
$returnString = 'Method called by $this'; | |
} else { | |
assert($callerIsSelf == false); | |
$returnString = 'Method not called by $this'; | |
} | |
return $returnString; | |
} | |
public function callGhostbusters() { | |
return $this->whosGonnaCall(); | |
} | |
} | |
class External { | |
public function callGhostbusters() { | |
$internal = new Internal(); | |
return $internal->whosGonnaCall(); | |
} | |
} | |
$internal = new Internal(); | |
$response = $internal->callGhostbusters(); | |
assert($response == 'Method called by $this'); | |
$external = new External(); | |
$response = $external->callGhostbusters(); | |
assert($response == 'Method not called by $this'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment