• Skip to content
  • Skip to primary sidebar
  • [ Home ]
  • [ WordPress Plugins Check ⋰ ]
  • [ Programming Review Main website ⋰ ]
  • Word of caution

WORDPRESS SHORT TRICKS AND SNIPPETS

WordPress ongoing blog

Namespaces in PHP (WordPress)

November 15, 2016 ⌛ Tagged With: namespaces, php, wordpress

Since the version 5.3 we have namespaces in PHP.
Here is how you would define one.

//Pizza.php
namespace Food;
class Pizza{
    public function eat(){
      return 'yummy!';
    }
}

You would call that like this:

//main.php
require 'Pizza.php';
$pizza = new \Food\Pizza();
echo $pizza->eat();

Or like this.

//main.php
require 'Pizza.php';
use Food\Pizza;
$pizza = new Pizza();
echo $pizza->eat();

Note that when you write use statement you can use both the notations.

use \Food\Pizza;
use Food\Pizza;

But the later one is my favorite.
This is not the case when you write the new statement

namespace Kings;
$pizza = new Super\Big\Pizza();
// "Class not found Kings\Super\Big\Pizza"

$pizza = new \Super\Big\Pizza();
// This works!

So it is always good to use \ after the new keyword.

Next, go ahead and shorten the long namespaces like this

use Kings\Big\Pizza as KBPizza;
$pizza = new KBPizza();

This will save you some keystrokes.

Tagged With: namespaces, php, wordpress

« Travis and PHP
Define constants in a WordPress plugin »

Primary Sidebar

Tags

.htaccess apache buddypress cdn command line css database debug debugging divi ecommerce editor editor styles emails featured image genesis google hooks html js linux menu items nginx php plugins query regex responsive rewrite rewrite rules security seo servers sql server theme themes wordpress thumbnails tips and tricks troubleshoot ubuntu URL web standards wordpress wp-cli zend

My WordPress Q&A site profile

profile for prosti at WordPress Development Stack Exchange, Q&A for WordPress developers and administrators

WORDPRESS SHORT TRICKS AND SNIPPETS

part of the programming-review.com ☂ since 2010