0

I have the following directory structure (only the important files shown):

app/
 - Http/                        
   - Controllers/
     - MyController.php         // namespace App\Http\Controllers
 - Utils/
   - InternalUtils/
     - Utility1.php             // namespace App\Utils\InternalUtils
     - Utility2.php             // namespace App\Utils\InternalUtils
     - ...
   - MyUtility.php             // namespace App\Utils

I am following the standard PSR-4 namespacing available in Laravel 5.

In the MyUtility.php file I am trying to use the following:

use InternalUtils\Utility1;
use InternalUtils\Utility2;
(new Utility1);   // works
$className = 'Utility1';
(new $className);   // throws Class 'Utility1' not found

Note that each Utility file is namespaced and contains a class name with the same name as Utility1.

The dynamic generation of objects is failing. Any ideas on what could be the issue?

8
  • 1
    try to use use \App\Utils\InternalUtils\Utility1; Commented Jul 13, 2015 at 8:03
  • 1
    you have to import the class by full namespace , so instead of use InternalUtils\Utility1; you have to use App\Utils\InternalUtils\Utility1; Commented Jul 13, 2015 at 8:05
  • @NoNameProvided That does not work either. Commented Jul 13, 2015 at 8:05
  • @NehalHasnayeen I tried importing via full namespace, but does not work. This is weird because I am able to use the full namespace from the controller and create an instance of the class. Commented Jul 13, 2015 at 8:07
  • 1
    clear your compiled file via artisan command Commented Jul 13, 2015 at 8:09

1 Answer 1

1

Please do as following

In your Utility1.php

<?php 

namespace App\Utils\InternalUtils;

Class Utility1 
{
    //code ....
}

In order to use the Utility1 class in MyUtility class, you can import full namespace

<?php 

namespace App\Utils;

use App\Utils\InternalUtils;   

class MyUtility 
{
    //other code 

    $utility1 = new InternalUtils\Utility1();
    $utility2 = new InternalUtils\Utility2();
}
Sign up to request clarification or add additional context in comments.

4 Comments

PHP doesn't allow you to import full namespaces!
@Jeemusu That's just how PHP works (or doesn't work). use App\Utils\InternalUtils; doesn't import anything.
@activatedgeek, change the use in your MyUtility class to use App\Utils\InternalUtils\Utility1; . Then initialise it with new Utility1();. Then do the same for utility2
@Jeemusu If I try generating the object dynamically from a string, this fails. Any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.