Skip to content

Instantly share code, notes, and snippets.

@szepeviktor
Last active November 27, 2019 06:43
Show Gist options
  • Save szepeviktor/ddb1bfd12d93accd318cc081637956ec to your computer and use it in GitHub Desktop.
Save szepeviktor/ddb1bfd12d93accd318cc081637956ec to your computer and use it in GitHub Desktop.
Connect to WordPress's global $wpdb instance from a class -> has a new home: https://github.com/szepeviktor/Toolkit4WP/blob/master/src/Db.php
<?php
/**
* This is a gift for Phil.
*
* Usage: $db = new \WordPress\WpDb(); $db->prepare('...');
*/
declare( strict_types = 1 );
namespace WordPress;
/**
* Connect to global $wpdb instance from a proper class.
*
* @see https://www.php.net/manual/en/language.oop5.magic.php
*/
class WpDb {
/**
* Get a property.
*
* @see https://codex.wordpress.org/Class_Reference/wpdb#Class_Variables
* @param string $name
* @return mixed
*/
public function __get( $name ) {
global $wpdb;
return $wpdb->$name;
}
/**
* Noop on set.
*
* @param string $name
* @param mixed $value
*/
public function __set( $name, $value ) {}
/**
* Execute a method.
*
* @see https://www.php.net/manual/en/language.oop5.overloading.php#object.call
* @param string $name
* @param array $arguments
* @return mixed
*/
public function __call( $name, $arguments ) {
global $wpdb;
return call_user_func_array( [ $wpdb, $name ], $arguments );
}
}
@szepeviktor
Copy link
Author

You can even use it with dependency injection.

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