Skip to content
Advertisement

Issues instantiating class in composition project

So I have a task to access an external api and then render the results to a separate FE. I have made an ApiClass and a ProductListClass. Then from an index page I am including the two class files and then am trying to call the ProductListClass method, but I am getting an ApiClass not found error and cant quite work out why, any help greatly appreciated

heres my ApiClass

JavaScript

This is my ProductListClass

JavaScript

And this is the index page

JavaScript

and this is the error I am getting

Fatal error: Uncaught Error: Class ‘ApiClass’ not found in /Applications/XAMPP/xamppfiles/htdocs/test/index.php:6 Stack trace: #0 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/test/index.php on line 6

Advertisement

Answer

You need to instantiate ApiClass from correct namespace, and fully qualified name (FQN) for your ApiClass is appApiClassApiClass. You need to either call

JavaScript

or use only class name by importing the namespace in the file header:

JavaScript

Namespaces are declared for each file, so that you could not change them by including files in different contexts. No namespace defined in the file means that it’s global namespace (like your ProductListClass).

GuzzleHttpClient

If you’re passing Client instance to your ApiClass you need to have it already instantiated and there’s no need to use new on it again. If you take FQN string as a parameter you may do that, but that’s not a good practice (unless you’re doing this kind of magic in some dependency injection library).

So either do this (preferred):

JavaScript

with api instantiation:

JavaScript

Or instantiate inside constructor without parameters:

JavaScript

Ps. I think you should learn to use Composer and its autoloading (automatic include class files) – working with libraries (and your own classes) will be much easier.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement