Easy Code Share > PHP > PHP Namespace Example Include Class, Function

PHP Namespace Example Include Class, Function


Namespace in programming implements an abstract concept. The re-usable PHP class, function, or constant of libraries and extensions are grouped to prevent from name collisions. In addition, Namespace aliasing increase readability of codes. The article uses PHP namespace example codes to explain the basics and its variation.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 5 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.
 DOWNLOAD SOURCE

 

SECTION 1
The Basics

PHP basically allow a namespace to include only classes, functions, and constants. Any PHP file can write case-insensitive expression to include namespaces. Also, there is a magic constant for namespaces to display itself.

 

Using a Namespace Class

This PHP namespace example code of ford groups a class, a function, and a constant. When any PHP file include it, the name of namespace is shown. The PHP magic constant __NAMESPACE__ in a namespace denotes its own name.

ford.php
<?php
namespace ford;
echo "<br>### namespace: " . __NAMESPACE__ . " loaded<br>";
class car {
    public $country = 'USA';
    public $models = [ "f-model-1"=>15000, "f-model-2"=>25000 ];
    public function getPrice($model_name) {
        return $this->models[$model_name];
    }
}
function buyCarFilter($budget, $models) {
    $result = [];
    foreach($models as $model=>$price) {
        if( $budget >= $models[$model]) $result[] = "$model ==> $price";
    }
    return $result;
}
const BUDGET = 26000;
?>

You must include a namespace file before using it. use ford\car announce that a class of the namespace will be used. The class has a member function getPrice() which will return a price for the specified car model.

index.php
<?php
require "ford.php";
/* namespace class */
use ford\car;
$car1 = new ford\car();
echo "<br>*** namespace class ***<br>";
$model = "f-model-1";
$price = $car1->getPrice($model);
echo "Price of $model is $price<br>";
echo "Made in $car1->country<br>";

Run it in browsers to see the result at the first stage.

%%% namespace: ford loaded
*** namespace class ***
Price of f-model-1 is 15000
Made in USA

 

Using a Namespace Constant

Namespace announcement is case-insensitive, so you can announce use ford\budget even though the constant is of uppercase. Actually, the constant is ford\BUDGET.

index.php
/* namespace constant */
use ford\budget; // case-insensitive
echo "<br>*** namespace constant ***<br>";
$budget = ford\BUDGET;
echo "Buyer's budget $budget<br>";

Run it in browsers to check the result.

*** namespace constant ***
Buyer's budget 26000

 

Using a Namespace Function

Subsequently, let us look at the function use ford\buycarfilter. Similarly, we can announce it by ignoring case of letters. The function is designed to filter the cars you can buy with a limited budget.

index.php
/* namespace function */
use ford\buycarfilter;
$result = ford\buyCarFilter($budget, $car1->models);
echo "<br>*** namespace function ***<br>";
echo "You are able to buy models of<br>";
foreach($result as $value) echo "$value<br>";

Obviously, you can buy all kinds of car models if budget is 26000.

*** namespace function ***
You are able to buy models of
f-model-1 ==> 15000
f-model-2 ==> 25000

 

SECTION 2
More Features

Moreover, PHP can define sub-namespaces, so the name of a namespace could be too long. Aliasing will help it reduce the length. In addition, more namespaces can be gathered in a PHP file.

 

Using Namespace Aliasing

Given a alias name by use ford\car as fcar, the shorter class name fcar can make your codes readable.

index.php
/* namespace alias */
use ford\car as fcar;
$car1 = new fcar();
echo "<br>*** namespace alias ***<br>";
$model = "f-model-2";
$price = $car1->getPrice($model);
echo "Price of $model is $price<br>";
echo "Made in $car1->country<br>";

Run it, you will find another model of car.

*** namespace alias ***
Price of f-model-2 is 25000
Made in USA

 

Multiple namespaces in a File

We write a file for another namespace which contains only a class definition. To be emphasized, you can merge files ford.php and toyota.php to be a file manufacturer.php. That is, many namepaces can be put in the same file.

toyota.php
<?php
namespace foreign\toyota;
echo "<br>%%% namespace: " . __NAMESPACE__ . " loaded<br>";
class car {
    public $country = 'JAPAN';
    public $models = [ "t-model-1"=>20000, "t-model-2"=>30000 ];
    public function getPrice($model_name) {
        return $this->models[$model_name];
    }
}
?>

 

Using a Sub-Namespace

Along with the previous example namespace foreign\toyota, let us discuss the topic of sub-namespace. Sometimes, you may want to design hierarchical groups of namespaces so that toyota cars belong to foreign manufacturers. PHP allow developers to classify namespaces in such a way.

index.php
/* sub-namespace */
require "toyota.php"; // You can merge ford.php and toyota.php into manufacturer.php
use foreign\toyota\car as tcar;
$car1 = new tcar();
echo "<br>*** sub-namespace ***<br>";
$model = "t-model-1";
$price = $car1->getPrice($model);
echo "Price of $model is $price<br>";
echo "Made in $car1->country<br>";

Run it in browsers to see that another namespace is loaded, and there are different models and manufacturer’s country.

%%% namespace: foreign\toyota loaded
*** sub-namespace ***
Price of t-model-1 is 20000
Made in JAPAN

All results of the PHP namespace example in browsers are shown as below.

PHP Namespace Example Execution Result

 

FINAL
Conclusion

Most PHP frameworks such as Laravel and Yii2 use PHP namespaces in developing templates. Our PHP namespace example codes here gives you the beginning tutorial so that you will have an overview about it.

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Suggested Reading

 

TRY IT
Quick Experience

That is all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.

 

Try It Yourself

Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.

Leave a Comment