Last active
June 23, 2018 04:15
-
-
Save johnpbloch/5246966 to your computer and use it in GitHub Desktop.
PHP 5.3+ "Global" provider pattern for WordPress
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 | |
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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());