PHP use Keyword

 The use keyword has two purposes: it tells a class to inherit a trait and it gives an alias to a namespace.

Consider a case where you have two classes with the same name; you'll find it strange, but when you are working with a big MVC structure, it happens. So if you have two classes with the same name, put them in different namespaces. Now consider when your auto loader is loading both classes (does by require), and you are about to use object of class. In this case, the compiler will get confused which class object to load among two. To help the compiler make a decision, you can use the use statement so that it can make a decision which one is going to be used on.

Example - 

create a trait and use it in a class

<?php
trait message1 {
  public function msg1() {
    echo "OOP is fun! ";
  }
}

class Welcome {
  use message1;
}

$obj = new Welcome();
$obj->msg1();
?>

Another example - 

namespace SMTP;

class Mailer{}

And

namespace Mailgun;

class Mailer{}

And if you want to use both Mailer classes at the same time then you can use an alias.

use SMTP\Mailer as SMTPMailer;

use Mailgun\Mailer as MailgunMailer;

Later in your code if you want to access those class objects then you can do the following:

$smtp_mailer = new SMTPMailer;

$mailgun_mailer = new MailgunMailer;

It will reference the original class.

Some may get confused that then of there are not Similar class names then there is no use of use keyword. Well, you can use __autoload($class) function which will be called automatically when use statement gets executed with the class to be used as an argument and this can help you to load the class at run-time on the fly as and when needed.

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...