PHP - Traits

 PHP support only single inheritance. Traits are a mechanism for code reuse in single inheritance languages such as PHP. A trait is intended to reduce some limitation of single inheritance by enabling a developer to reuse set of method freely in several independent classes living in different class hierarchies.

PHP support only single inheritance : A child class can inherit only from one single parent. 

If a class need multiple behaviors - OOPS traits solve this problem.  

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

Traits are declared with the trait keyword:

Syntax - 

<?php
trait TraitName {
  // some code...
}
?>

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

<?php
class Base {
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait 
SayWorld {
    public function 
sayHello() {
        
parent::sayHello();
        echo 
'World!';
    }
}

class 
MyHelloWorld extends Base {
    use 
SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
?>

Multiple traits - 

Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas.

<?php
trait Hello {
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait 
World {
    public function 
sayWorld() {
        echo 
'World';
    }
}

class 
MyHelloWorld {
    use 
HelloWorld;
    public function 
sayExclamationMark() {
        echo 
'!';
    }
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>

If two Traits insert a method with the same name, a fatal error is produced, if the conflict is not explicitly resolved.

To resolve naming conflicts between Traits used in the same class, the insteadof operator needs to be used to choose exactly one of the conflicting methods.

Since this only allows one to exclude methods, the as operator can be used to add an alias to one of the methods. Note the as operator does not rename the method and it does not affect any other method either.

<?php
trait {
    public function 
smallTalk() {
        echo 
'a';
    }
    public function 
bigTalk() {
        echo 
'A';
    }
}

trait 
{
    public function 
smallTalk() {
        echo 
'b';
    }
    public function 
bigTalk() {
        echo 
'B';
    }
}

class 
Talker {
    use 
A{
        
B::smallTalk insteadof A;
        
A::bigTalk insteadof B;
    }
}

class 
Aliased_Talker {
    use 
A{
        
B::smallTalk insteadof A;
        
A::bigTalk insteadof B;
        
B::bigTalk as talk;
    }
}
?>

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.

PHP Namespace

 Namespaces are programming language mechanism for organizing function, variable and classes. PHP 5.3 add support for namespace. Namespaces solve two different problems.

1-  They allow for better organization by grouping classes that work together to perform a task

2- They allow the same name to be used more than one class

Example - you may have a set of classes which describe an HTML table, such as Table, Row and Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed. Namespaces can be used to organize the classes into two different groups while also preventing the two classes Table and Table from being mixed up.

Declaring a namespace - 

namespace are declared at the beginning of a file sing the namespace keyword.

syntax - 

namespace HTML;

Note - 

 A namespace declaration must be the first thing in the PHP file. The following code would be invalid:

<?php

echo "Hello PHP";

namespace HTML;

.........

?>

Constants, classes and functions declared in this file will belong to the Html namespace:

Example - 

Create a Table class in the Html namespace:

<?php
namespace Html;
class Table {
  public $title = "";
  public $numRows = 0;
  public function message() {
    echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
  }
}
$table = new Table();
$table->title = "My table";
$table->numRows = 5;
?>

<!DOCTYPE html>
<html>
<body>

<?php
$table->message();
?>

</body>
</html>

For further organization, it is possible to have nested namespaces:

syntax - 

Declare a namespace called Html inside a namespace called Code:

namespace Code\Html;

Using Namespaces - 

Any code that follows a namespace declaration is operating inside the namespace, so classes that belong to the namespace can be instantiated without any qualifiers. To access classes from outside a namespace, the class needs to have the namespace attached to it.

Example - 

Use classes from the Html namespace:

$table = new Html\Table()
$row = new Html\Row();

When many classes from the same namespace are being used at the same time, it is easier to use the namespace keyword:

Example - 

Use classes from the Html namespace without the need for the Html\qualifier:

namespace Html;
$table = new Table();
$row = new Row();

Namespace Alias - 

It can be useful to give a namespace or class an alias to make it easier to write. This is done with the use keyword:

Example -

given a namespace alias 

use Html as H;
$table = new H\Table();


---------------------------

use Html\Table as T;
$table = new T();


PHP echo and print Statements

 In PHP echo and print are both used for output the data to the screen. The echo and print statements, are not function but are language constructs. 

The difference between echo and print are small : echo has no return value while print has a return value 1.  so it can be used in expression. 

echo can take multiple parameters while print can take one parameters. 

echo is marginally faster tha print.

echo Statement -

the echo statement can be used with or without  parentheses echo or echo ().

<?php

echo "<h2>PHP is Fun!</h2>";

echo "Hello world!<br>";

echo "I'm about to learn PHP!<br>";

echo "This ", "string ", "was ", "made ", "with multiple parameters.";

echo ("This ", "string ", "was ", "made ", "with multiple parameters.");

?> 


print statement -

print statement can be used with or without parenthesis: print or print().

<?php
$txt1 = "Learn PHP";
$txt2 = "wartalab.blogspot.com";
$x = 5;
$y = 4;

print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>

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)   {   $...