Skip to content

Instantly share code, notes, and snippets.

@johnpbloch
Last active June 23, 2018 04:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johnpbloch/5246966 to your computer and use it in GitHub Desktop.
Save johnpbloch/5246966 to your computer and use it in GitHub Desktop.
PHP 5.3+ "Global" provider pattern for WordPress
<?php
// Here we are, in any scope imaginable. It doesn't matter which
$my_object = new My_Class();
add_filter( 'jpb.provider.my_class', function() use ( $my_object ) {
return $my_object || new My_Class();
} );
// This is in the global scope
function get_my_class_instance() {
$obj = apply_filters( 'jpb.provider.my_class', false );
if( ! $obj ) {
throw new Exception( "This is embarassing, isn't it?" );
}
return $obj;
}
@engelen
Copy link

engelen commented Apr 3, 2013

An interesting approach... However, in its current form it will not work, as the
return $my_object || new My_Class();
statement causes the function to return true (in this case), as PHP will handle this as
return ($my_object || new My_Class());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment