Skip to content

Instantly share code, notes, and snippets.

@peterwilsoncc
Last active December 20, 2015 14:19
Show Gist options
  • Save peterwilsoncc/6145280 to your computer and use it in GitHub Desktop.
Save peterwilsoncc/6145280 to your computer and use it in GitHub Desktop.
Experimenting with singletons for WordPress themes - it makes it easier than dozens of calls to function_exists(), I think. Maybe.
<?php
/* Child Theme's functions.php */
function collaborate_class_init() {
class Collaborate extends Collaborate_Parent_Theme {
public static function theme() {
if ( ! Collaborate::$instance instanceof self ) {
Collaborate::$instance = new self();
}
return Collaborate::$instance;
}
protected function __construct() {
parent::__construct();
// init any child specific stuff here
}
public function testing_un_dos_tres() {
echo 'child';
}
}
}
/* Parent Theme's functions.php */
class Collaborate_Parent_Theme {
protected static $instance;
public static function theme() {
if ( ! Collaborate_Parent_Theme::$instance instanceof self ) {
Collaborate_Parent_Theme::$instance = new self();
}
return Collaborate_Parent_Theme::$instance;
}
protected function __construct() {
// init any theme stuff here
}
public function testing_un_dos_tres() {
echo 'parent';
}
}
if ( ! function_exists( 'collaborate_class_init' ) ) {
function collaborate_class_init() {
class Collaborate extends Collaborate_Parent_Theme {
public static function theme() {
if ( ! Collaborate::$instance instanceof self ) {
Collaborate::$instance = new self();
}
return Collaborate::$instance;
}
}
}
}
/* Testing shit */
collaborate_class_init();
Collaborate::theme();
function scope_testing() {
Collaborate::theme();
Collaborate::theme()->testing_un_dos_tres();
}
scope_testing();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment