Skip to content

Instantly share code, notes, and snippets.

@PCianes
Created July 5, 2017 09:39
Show Gist options
  • Select an option

  • Save PCianes/6c4ee79ceea995f61ecd33dfeb04fbac to your computer and use it in GitHub Desktop.

Select an option

Save PCianes/6c4ee79ceea995f61ecd33dfeb04fbac to your computer and use it in GitHub Desktop.
Migrate from prefixing convention to PHP namespacing
<?php
/**
* Description
*
* @package ${NAMESPACE}
* @since 1.0.0
* @author hellofromTonya
* @link https://KnowTheCode.io
* @license GNU-2.0+
*/
namespace KnowTheCode\Root;
// aliasing
use KnowTheCode\InsOutsPHPNamespacing\Sandbox as sandbox;
// import a function using PHP 5.6 and up
use function KnowTheCode\InsOutsPHPNamespacing\Sandbox\{get_the_ID, get_post_id};
function get_the_other_ID() {
ddd( 'yup it worked');
}
//Sandbox\get_the_ID();
\KnowTheCode\InsOutsPHPNamespacing\Sandbox\get_post_id();
sandbox\get_post_id();
get_post_id();
//\get_the_ID();
<?php
/**
* Description
*
* @package ${NAMESPACE}
* @since 1.0.0
* @author hellofromTonya
* @link https://KnowTheCode.io
* @license GNU-2.0+
*/
namespace KnowTheCode\Root;
// aliasing
use KnowTheCode\InsOutsPHPNamespacing\Sandbox as sandbox;
// import a function using PHP 5.6 and up
use function KnowTheCode\InsOutsPHPNamespacing\Sandbox\get_the_ID;
use function KnowTheCode\InsOutsPHPNamespacing\Sandbox\get_post_id;
function get_the_other_ID() {
ddd( 'yup it worked');
}
// relative naming
Sandbox\get_the_ID();
// fully qualified name
\KnowTheCode\InsOutsPHPNamespacing\Sandbox\get_the_ID();
// alias naming
sandbox\get_the_ID();
// importing with PHP 5.6 and up
get_the_ID();
// this is one out of WordPress Core.
//\get_the_ID();
@PCianes
Copy link
Author

PCianes commented Jul 5, 2017

WP_Query is not namespaced. Therefore you have two choices:

  1. You can use the fully qualified class name in the code like this:

$query = new \WP_Query( $args );

  1. Import first to avoid having to use the backslash namespace separator:

use WP_Query

Then the query code is this:

$query = new WP_Query( $args );

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