0
0
PHPprogramming~5 mins

Importing with use keyword in PHP

Choose your learning style9 modes available
Introduction

The use keyword helps you bring code from other places into your file so you can use it easily without writing full names every time.

When you want to use a class or function from another folder or namespace.
When you want to make your code shorter and easier to read.
When you want to avoid writing long names repeatedly.
When you want to organize your code better by separating parts into different files.
When you want to rename an imported class or function to avoid name conflicts.
Syntax
PHP
<?php
use Namespace\SubNamespace\ClassName;

// or with alias
use Namespace\SubNamespace\ClassName as AliasName;

The use statement must be placed at the top of your PHP file, after the <?php tag and before any other code.

You can import multiple classes or functions by writing multiple use lines.

Examples
This imports the User class from the App\Models namespace so you can create a new user easily.
PHP
<?php
use App\Models\User;

$user = new User();
This imports the Formatter class but renames it to Fmt to keep the code shorter.
PHP
<?php
use App\Helpers\Formatter as Fmt;

echo Fmt::formatDate('2024-06-01');
This imports a function named calculateSum from a namespace so you can call it directly.
PHP
<?php
use function App\Utils\calculateSum;

$result = calculateSum(5, 10);
Sample Program

This program defines a User class in one namespace and then imports it in another namespace using use. It creates a User object and calls its greet method.

PHP
<?php
namespace App\Models;

class User {
    public function greet() {
        return "Hello from User!";
    }
}

namespace App\Main;

use App\Models\User;

$user = new User();
echo $user->greet();
OutputSuccess
Important Notes

If you forget to import a class with use, PHP will look for it in the current namespace and may give an error if not found.

You can import classes, functions, and constants using use with slightly different syntax.

Using aliases with as helps when two imported classes have the same name.

Summary

The use keyword imports code from other namespaces or files to make your code cleaner.

Place use statements at the top of your PHP file after <?php.

You can rename imports with as to avoid name conflicts or shorten names.