One of the advantage of Php namespaces is, you can create aliases to the existing entities.
Let’s see it with an example.
dynamic_logger.php
<?php
namespace DynamicLogger;
class Logger{
public function log(){
echo "I am dynamic logger\n";
}
}
?>
logger.php
<?php
namespace CustomLogger;
class Logger{
public function log(){
echo "I am custom logger\n";
}
}
?>
Let’s create alias names to Logger classes present in DynamicLogger and CustomLogger namespaces.
use DynamicLogger\Logger as MyDynamicLogger;
use CustomLogger\Logger as MyCustomLogger;
Find the below working application.
aliases.php
#!/usr/bin/php
<?php
include 'logger.php';
include 'dynamic_logger.php';
use DynamicLogger\Logger as MyDynamicLogger;
use CustomLogger\Logger as MyCustomLogger;
$dyn_logger = new MyDynamicLogger();
$cust_logger = new MyCustomLogger;
$dyn_logger->log();
$cust_logger->log();
?>
Output
$./aliases.php
I am dynamic logger
I am custom logger
Previous Next Home
No comments:
Post a Comment