Иван Желев Иван Желев - 1 year ago 125
PHP Question

How to import several sub-namespaces on PHP

I have this code

use App\Entities\Job;
use App\Entities\Category;
use App\Entities\City;
use App\Entities\JobType;

$viewModel['categories']= Category::all();
$viewModel['cities'] = City::all();
$viewModel['jobTypes'] = JobType::all();

I would like to avoid repetition and just put once something like
use App\Entities\*
and import all names behind

Usually on frameworks such as Laravel one may need to import many models or classes to work with them, and it would be easier if a generic
construct existed.

Answer Source

Starting with PHP 7 you can write:

use App\Entities\{Job, Category, City, JobType};

PHP 5 doesn't provide such a shortcut.

See http://php.net/manual/en/migration70.new-features.php for other changes in PHP 7.


As @alister-bulman suggests in a comment below, the best you can do in PHP 5 is to declare the namespace of the classes you use (maybe with an alias that is shorter than its name) and then specify the names of the classes relative to this namespace.

For example:

use App\Entities as E;

$viewModel['categories']= E\Category::all();
$viewModel['cities'] = E\City::all();
$viewModel['jobTypes'] = E\JobType::all();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download