0

I'm using codeigniter 4 but when I try to call my own library I get the error Undefined variable: utils.

here's my code:

/app/libraries/Utils.php

<?php

namespace App\Libraries;

class Utils
{
    function generateRandomString($length = 10) {
        return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
    }
}

/app/Controllers/Users.php

<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\UserModel;
use App\Libraries\Utils;

class Users extends ResourceController
{
    ...
    public function do_reset_password()
    {
        $utils = new Utils();
        $str = $utils->generateRandomString(); // the error points to this line
    ...
dapidmini
  • 1,490
  • 2
  • 23
  • 46
  • 1
    please have a look here: https://stackoverflow.com/questions/58900176/codeigniter-4-autoload-library – Vickel Aug 04 '22 at 19:05

2 Answers2

0

You should place your file Utils.php in /app/Libraries

example project structure

Do not create your own libraries directory in root project.

Doelmi
  • 150
  • 7
  • sorry I made a typo when writing the Utils.php location. after I rechecked, the Utils.php is already in /app/Libraries/Utils.php. I edited the path in the question. – dapidmini Aug 05 '22 at 16:34
  • do you have any screeshoot of that error? `Undefined variable: utils` – Doelmi Aug 07 '22 at 07:52
0

In your use line what happens if you do this:

use App\Libraries\Utils as MyUtils; and call $utils = new MyUtils instead?

Please also make sure your Libraries folder begins with a capital L.

Antony
  • 3,875
  • 30
  • 32