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?
Yes it is bad practice; no it's not. But you'll get better performance out of your code if you avoid using __autoload . And to maintain your code, it's better to put all your includes at the top of the script like you would for import statements in other languages. I would suggest consistency.
Example: After an object is instantiated, you can access the property of a class using the object and -> operator. Any member declared with keyword "private" or "protected" cannot be accessed outside the method of the class.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With