class not found php namespace

PHP class not found when using namespace

I am new with this namespace thing.

class1.php

class2.php

PHP Fatal error: Class ‘Timer’ not found in path/to/class2.php at line ***

I read somewhere on SO, that I need to create Autoloaders for this. If so, how do I approach into creating one, and if not, then what else is the issue?

UPDATE

I created an Autoloader which will require all the required files on top of my php script. So, now the class2.php would end up like this.

2 Answers 2

We can solve the namespace problem in two ways

The First Way (Namespace and require) way

The Second Way (Using Composer and the autoloading way)

Make composer.json file. According to your example «src/Utility» We need to create a composer.json file before the src folder. Example: In a folder called myApp you will have composer.json file and a src folder.

Now go to that folder open your terminal in the folder location where there is composer.json file. Now type in the terminal!

This will create a vendor folder. Therefore if you have a folder named «MyApp» you will see vendor folder, src folder and a composer.json file

Verification.php (Verification Class)

This method is more powerful when you have a complex folder structure!!

Источник

Cannot find Class with PHP Namespace

I posted some questions previously regarding the use of Namespaces in PHP and from what I got, this example code I have below should be working.

However I am getting errors when I try to use Namespace in PHP like this. Here is the first error when running the code below as is.

As you can see I tried to make it as simple as possible just to get the Namespace part working. I have tried different variations and cannot seem to figure it out.

5 Answers 5

Even when using use statement, you need to specify the namespace of the class you are trying to instantiate. There are a lot of examples here: http://www.php.net/manual/en/language.namespaces.importing.php

You can read more about it in the manual about namespaces.

Читайте также:  Speechruntime exe что это

1 Its called «Full-qualified classname», if you name a class with its complete name.

\Controller would be a class in the global (default) namespace, i.e. as if you used no namespace at all.

Strangely I have found that in my example code from the Question above, if I change all the Namespace’s that are defined to something like MyLibrary so it would be like this code below.

E:\Library\Registry.class.php File

Then when I use use MyLibrary\Registry; in another file, I am able to access it how I had planned.

The reason this is very strange to me is this now makes a class name appear to be a Namespace as well. So I would not need to set a Namespace to ‘MyLibrary\Library’ to access the Registry instead I would do it like I showed in this answer to be able to access it with just calling the name of the class.

I hope this makes sense and helps someone else. I will not accept this as the answer as I am hoping someone with more know-how will come in and post a better Answer with explanation

Источник

PHP class not found but it’s included

I’m including a PHP class with

but when the code is executed i receive this error:

Fatal error: Class ‘User’ not found in C:\xampp\htdocs\WebName\resources\engine\ajax\signup.php on line 12

I still can’t figure out what’s the problem. I’m 99% sure it’s correct.

The «$ENGINE» is correct, and the class is correct too (Netbeans suggests me class methods and variables).

18 Answers 18

Check to make sure your environment isn’t being picky about your opening tags. My configuration requires:

Then I get the same error as you.

I had this problem and the solution was namespaces. The included file was included in its own namespace. Obvious thing, easy to overlook.

Or you forget to add a classmap to the composer, thus classes are not autoloaded and are not available. For example,

The problem went away when I did

As a more systematic and structured solution you could define folders where your classes are stored and create an autoloader ( __autoload() ) which will search the class files in defined places:

Читайте также:  механические средства дезинфекции что к ним относится

It ‘happened to me! The problem is that somehow you include a file with the same file name of the class thus invalidating the same class!

Check the path of inclusion and these checks files with the same name!

Check your file permissions for the correct linux user for classUser.php

In fact, it’s a very old thread but useful.

When namespace declaration is part of your php class file «this kind of weird errors tends to appear».

Sometimes an inaccessible or corrupted file would be the problem, as was in my case

you should declare namespace in the ClassUser.php, something like this:

Then you can add the class in your other php files like this:

and you are done. Otherwize it will abuse:

My fail might be useful to someone, so I thought I would post as I finally figured out what the issue was. I was autoloading classes like this:

In my /classes folder I had 4 classes:

When I later created a new class called:

I ended up naming my DbObject class to _dbobject.class.php and it always loads that first.

I realize my naming conventions are probably not great and that’s why I was having issues. But I’m new to OOP so doing my best.

Источник

Пишет Class not found. Как правильно определить пространство имен?

От корня сайта создал класс:
/bitrix/templates/app/Pi/Test.php
Класс:

Пробую подключить в другом файле и заставить отработать:

Но пишет Class ‘app\Pi\test’ not found

С точки зрения архитектуры (рекомендую изучить документацию, она очень обширна и познавательна) все компоненты должны лежать в так называемом пространстве имен, чем обычно служит ник-нейм или название компании (Естественно начинается не с цифры и содержит только латинские буквы), которые в свою очередь могут располагаться в /bitix/components/#пространство_имен#/#название_компонента#/

Теперь построчно разберем Ваш вопрос:

Вы положили свой класс сюда: /bitrix/templates/app/Pi/Test.php, что является неверным с точки зрения архитектуры, так как поместили класс отвечающий за контроллер в папку с шаблоном. Если вы не пишете свой модуль вы можете подключить его например в /local/php_interface/classes/ (пример надуманный, можете просто в /local/php_interface положить или сразу в init.php), однако для этого вы должны будете написать autoloader, так как у битрикса он работает только для модулей. Предположим вы в init.php напишете грубый require_once с файлом.

Читайте также:  Что такое полимерная пленка

Затем вы делаете следующее:

Что является неверным, так как по сути вы обьявляете неймспейс для файла и это с точки зрения php выглядит вот так в конечном итоге:

А класса app\Pi\CBitrixComponent не существует. Так что вам нужно поправить пример хотя бы так:

class test extends \CBitrixComponent

Настоятельно рекомендую прочитать документацию или хотя бы посмотреть видео с академии битрикс. Сама система не подарок, а другой программист который увидит ваш код будет говорить что это битрикс виноват.

Источник

After 4 years of absence in PHP programming I’m trying to make some new project in it.

I’m collecting some useful libraries. And I have problem with «use» keyword. Here is my part of code where error is thrown.

And I’m getting error:

I thought that is maybe something wrong with include_path in php.ini, but it looks like that:

Did I miss something?

BTW. I’m using nginx + php-fpm.

1 Answer 1

The use keyword does not actually include any files. I’m afraid you either have to register an autoload function with the spl_register_autoload() call, or manually include the files.

Usually a good default autoloader will look for files following the same path as the namespaces, like this:

More on autloading in PHP, a structure that many (newer) projects are following: http://groups.google.com/group/php-standards/web/psr-0-final-proposal

Not the answer you’re looking for? Browse other questions tagged php or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Образовательный портал