Use inside class versus outside class

Zoe Zoe
Zoe Zoe used Ask the Experts™
on
Recently, I've had to put Use inside a class but I've always seen it put outside the class. What's the difference? When do I need to put it inside and when do I need to put it outside? If I put it outside, I get an error saying that I have an undefined method.

class MY_Controller extends CI_Controller
{
	use Auth;
}

Open in new window


use Auth;
class MY_Controller extends CI_Controller
{
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
I suspect Auth is a trait

Refer to the documentation here

http://php.net/manual/en/language.oop5.traits.php
Top Expert 2015
Commented:
Hi


The purpose of USE is to  bring one class from another namespace, but functionally there is no difference. Using USE will help you change your implementation with ease as you only need to make changes in few places only. Also if the namespaces path is long then it might be difficult to type the whole path each time when one need to instantiate that class.
Most Valuable Expert 2011
Top Expert 2016
Commented:
The keyword "use" is overloaded in PHP and can have more than one meaning.  Here are some of the references.  In my opinion, multiple inheritance is an anti-pattern with lots of potential for confusion among team members.  I recommend avoiding it.  Namespaces, OTOH reduce the risk of confusion.  And auto-loading is a necessity.

http://php.net/manual/en/language.namespaces.basics.php
http://php.net/manual/en/language.namespaces.faq.php
http://php.net/manual/en/language.oop5.traits.php
http://php.net/manual/en/function.trait-exists.php
http://php.net/manual/en/language.oop5.autoload.php

"Use" is also part of that curious admixture of scopes in PHP's implementation of lambda functions.

http://php.net/manual/en/functions.anonymous.php
http://php.net/manual/en/class.closure.php

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial