Skip to content

Instantly share code, notes, and snippets.

@szepeviktor szepeviktor/_core-wpdb.php
Last active Nov 27, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

szepeviktor commented Jun 9, 2019

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
You can’t perform that action at this time.