1

In PHP Laravel I want to create class with properties, class like DTO. In App\Entity I created class:

<?php

namespace App\Entity\DTO;

class UserDTO
{
    public $id;
}

And I want to use it in my Controller

<?php

namespace App\Http\Controllers;

use App\Entity\DTO;

class UserApiController extends Controller
{
    public function loginPost(Request $request)
    {
      ...
      $userDTO = new UserDTO();
      $userDTO->id = $user->id;
    }
}

And I have error:

Error: Class 'App\Http\Controllers\UserDTO' not found in file C:\xampp\htdocs\testsapp\app\Http\Controllers\UserApiController.php on line 131
#0 [internal function]: App\Http\Controllers\UserApiController->loginPost(Object(Illuminate\Http\Request))
#1 C:\xampp\htdocs\testsapp\vendor\laravel\framework\src\Illuminate\Routing\Controller.php(54): call_user_func_array(Array, Array)

It's looking for UserDTO in App\Http\Controllers nampespace. Don't see use App\Entity\DTO;

2
  • 2
    Try to replace use App\Entity\DTO; to use App\Entity\DTO\UserDTO; Commented Aug 16, 2020 at 2:40
  • You may want to have a look at JsonSerializeable. Commented Aug 16, 2020 at 2:55

1 Answer 1

2

There is no actual "importing" that happens in PHP, everything is just an alias. You are aliasing App\Entity\DTO to DTO in this file, so to reference your DTO you would need to use DTO\UserDTO:

new DTO\UserDTO;

You are not importing everything inside DTO when you use the statement use App\Entity\DTO;; this is the equivalent of use App\Entity\DTO as DTO;

You can also just alias this class directly:

use App\Entity\DTO\UserDTO;

...

... new UserDTO;
Sign up to request clarification or add additional context in comments.

Comments

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.