Skip to content

Globally Set an Option in PHP

Here’s a pattern I was only vaguely aware of, until recently:

function stripMedia(bool $value = null): bool
{
  static $stripMedia = true; // Default setting.

  if ($value !== null) {
    $stripMedia = $value;
  }

  return $stripMedia;
}

In a function—this could be a global helper function, although I guess it’d work for static methods too—declare a variable as static to prevent it from being garbage-collected after the function has run. That is, next time you call, in our case, stripMedia(), it’ll have “remembered” whatever argument you passed it before.

You’d use it by calling it with an argument, like stripMedia(false), which would set the value, before doing “something,” and then inside that “something,” you use that value:

if (stripMedia()) {
  // Do a certain thing.
}

A cleaner version of define('STRIP_MEDIA', false) (which you could set only once and thus isn’t very flexible) or $GLOBALS['stripMedia'] = false or similar (which is just nasty)?