Skip to content

Instantly share code, notes, and snippets.

@grok
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grok/11156603 to your computer and use it in GitHub Desktop.
Save grok/11156603 to your computer and use it in GitHub Desktop.
This is an example of properly using nested functions within PHP, as well as the improper way. It outlines that improper use throws the function into the global scope. In general I would recommend not using nested functions. It dirties things up.
<?php
class Example {
// This is not intended to be accessible outside this class.
private function _hidden() {
// This is not acceptable. This becomes global.
// also unable to declare this as private vs. public - it generates a parse error.
function _shouldbehidden() {
$backtrace = debug_backtrace();
$caller = isset($backtrace[1]['function']) ? $backtrace[1]['function'] : FALSE;
if($caller == '_hidden') {
echo '>> GOOD: PUBLICLY EXPOSED VIA INTENTIONAL METHOD!' . "\n";
} else {
echo '>> BAD: UNINTENTIONALLY EXPOSED! :(' . "\n";
};
echo 'Called Nested Method: '. __FUNCTION__ . "\n";
}
_shouldbehidden();
// This is acceptable. Scope is preserved.
$_anon_hidden = function () {
echo 'Called Anonymous Nested Method: '. __FUNCTION__ . "\n";
};
$_anon_hidden(); // Works in here
echo 'Called Method: '. __FUNCTION__ . "\n";
}
// This is an intentional exposing, which makes it OK.
public function useme() {
$this->_hidden(); // This works.
// FATAL ERROR
// $this->_hidden->_shouldbehidden(); // Cannot access.
echo 'Called Method: '. __FUNCTION__ . "\n";
}
}
// Instianitate
$example = new Example();
// Calling Example::useme() works as expected
$example->useme();
// This fails, since _shouldbehidden() is not a method of Example, even though it was defined in Example::_shouldbehidden()
// FATAL ERROR
// $example->_shouldbehidden();
// _shouldbehidden(), defined in Example::_hidden(), is now in the global scope, so the following works.
_shouldbehidden(); // << BAD ... this ended up in the global scope. Probably unintentionally.
// FATAL ERROR
// $_anon_hidden(); // This is hidden as expected.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment