Last active
November 27, 2019 06:43
-
-
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
This file contains 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 | |
/** | |
* 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 ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can even use it with dependency injection.