Skip to content

Instantly share code, notes, and snippets.

@jk
Last active August 29, 2015 14:03
Show Gist options
  • Save jk/0f4d4f216dea407b9631 to your computer and use it in GitHub Desktop.
Save jk/0f4d4f216dea407b9631 to your computer and use it in GitHub Desktop.
Detect if a method call was from inside the class or outside
<?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