Introduction
Sub-namespaces help organize code into smaller groups inside bigger groups. This keeps code neat and avoids name clashes.
Sub-namespaces help organize code into smaller groups inside bigger groups. This keeps code neat and avoids name clashes.
<?php namespace MainNamespace\SubNamespace; class MyClass { // class code here }
App\Controllers sub-namespace.<?php namespace App\Controllers; class HomeController { // code }
App\Models\User.<?php namespace App\Models\User; function getUser() { // code }
Feature is inside a three-level sub-namespace.<?php namespace Company\Project\Module; class Feature { // code }
This program defines a Book class inside the Library\Books sub-namespace. It creates an object and prints the book title.
<?php namespace Library\Books; class Book { public function getTitle() { return "Learning PHP"; } } // Using the class $book = new Book(); echo $book->getTitle();
Remember to use the full namespace path when using classes from sub-namespaces outside their namespace.
You can use the use keyword to import sub-namespaces for easier access.
Sub-namespaces organize code into smaller groups inside bigger groups.
They help avoid name conflicts and keep code clean.
Use backslashes (\) to separate namespace levels.
App\Controllers?namespace App\Models\User;
class Profile {
public function getName() {
return "Alice";
}
}
$profile = new \App\Models\User\Profile();
echo $profile->getName();namespace App\Services\Payment
class Processor {
public function pay() {
return "Paid";
}
}namespace App\Utils\String;
class Formatter {
public static function format() {
return "Formatted String";
}
}
namespace App\Utils\Number;
class Formatter {
public static function format() {
return 12345;
}
}
// In global namespace
use App\Utils\String\Formatter as StringFormatter;
use App\Utils\Number\Formatter as NumberFormatter;
echo StringFormatter::format() . " and " . NumberFormatter::format();Pass the test and this pattern moves unknown