PHP : 'use' inside of the class definition

PhpOopNamespacesMultiple Inheritance

Php Problem Overview


Recently I came across a class that uses use statement inside of the class definition.

Could someone explain what exactly does it do - as I can't find any information about it.

I understand that it might be a way of moving it away form a global scope of the given file, but does it perhaps allow the given class inherit from multiple parent classes as well - since extends only allows one parent class reference?

The example I saw was in the User model of the original installation of Laravel:

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

	use UserTrait, RemindableTrait;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('password', 'remember_token');

}

and I've seen some examples of this model actually using methods included within the UserTrait class - hence my suspicion, but would really like to find out more about the meaning of the enclosed use statements.

PHP documentation says:

> The use keyword must be declared in the outermost scope of a file (the > global scope) or inside namespace declarations. This is because the > importing is done at compile time and not runtime, so it cannot be > block scoped. The following example will show an illegal use of the > use keyword:

followed by the example:

namespace Languages;

class Greenlandic
{
    use Languages\Danish;

    ...
}

which would indicate that it is an incorrect use of the use keyword - any clues?

Php Solutions


Solution 1 - Php

They are called Traits and are available since PHP 5.4. They are imported into another class or namespace using use keyword which is included since PHP 5.0 like importing a regular class into another class. They are single inheritance. The primary reason for the implementation of traits is because of the limitation of single inheritance.

For more details see the PHP trait manual:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSebastian SulinskiView Question on Stackoverflow
Solution 1 - PhpSagar RabadiyaView Answer on Stackoverflow