Atsa'am
Atsa'am

Reputation: 27

How do I resolve missing class function in codeigniter?

I have this in my controller:

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
use xampp\htdocs\client\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet;
use xampp\htdocs\client\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx;

But here is the error I am seeing after running the code

 Message: Class 'xampp\htdocs\client\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet' not found
    
  Filename: C:\xampp\htdocs\client\application\controllers\admin\Home.php

Upvotes: -1

Views: 71

Answers (1)

IMSoP
IMSoP

Reputation: 97688

You appear to have confused use and include/require.

A use statement is for namespace importing and aliasing. It says "when I use the class name Foo, what I actually mean is Something\Something\Foo. That full name may look like a Windows file path, but the \ here is actually PHP's namespace separator, and doesn't directly relate to the location on disk.

In this case, you would write:

// Alias these class name so I don't have to write them in full in this file
use PhpSpreadsheet\Spreadsheet;
use PhpSpreadsheet\Writer\Xlsx;

If you want to reference the code in a particular file, you need the include and require family of keywords. Those say "load this PHP file, and execute the code in it, including class and function definitions.

So the following would make sense:

// Load the file
require_once 'xampp\htdocs\client\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet.php';
require_once 'xampp\htdocs\client\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx.php';

However, most PHP libraries are built to be autoloaded, so you don't have to name each file manually. Generally, you don't even need to configure the autoloading itself, instead you'd use Composer to install them, and it would set up the autoloader for you.

You would then write, in the main entry point of your code:

require_once 'vendor/autoload.php';

And the classes would be loaded automatically when referenced. Note that you probably still want the use lines, though, and those do have to be in each file (because each file can use the same alias to reference different classes).

Upvotes: 1

Related Questions