Fatal error cannot use because the name is already in use

[BUG] [Symfony 3.0] [PHP 7] Cannot declare class Locale, because the name is already in use #20532 Comments I got the following error in the console, when using a translation within a twig file (not sure if it’s only in twig): Info about environment: xenial+1 (cli) ( NTS ) Symfony 3.0.1 The text was […]

Содержание

  1. [BUG] [Symfony 3.0] [PHP 7] Cannot declare class Locale, because the name is already in use #20532
  2. Comments
  3. Cannot declare class because the name is already in use #374
  4. Comments
  5. Ошибка Cannot declare class
  6. Cannot declare class m140209_132017_init, because the name is already in use #13989
  7. Comments
  8. What steps will reproduce the problem?
  9. What is the expected result?
  10. What do you get instead?
  11. Additional info
  12. Footer

[BUG] [Symfony 3.0] [PHP 7] Cannot declare class Locale, because the name is already in use #20532

I got the following error in the console, when using a translation within a twig file (not sure if it’s only in twig):

Info about environment:

xenial+1 (cli) ( NTS )
Symfony 3.0.1

The text was updated successfully, but these errors were encountered:

This looks weird. Can you explain which step you performed that ended up here? Did you switch PHP versions, but did not clear the cache?

First I upgraded to 3.0.1, after a succesful upgrade, i switched to PHP 7.0. I can confirm this issue is not a cache issue. I forced cleared the cache by removing the folder cache content (rm ./var/cache/prod/; rm ./var/cache/dev/), but that does not solve anything.

I got the issue!

The following rule causes the error:
$c = SymfonyComponentLocaleLocale::getDisplayCountries(‘nl’);

I replaced the code with the following code:
$c = Intl::getRegionBundle()->getCountryNames(‘nl’);

But this strange (Declare) error should not may appear!

Same here with Symfony 3.2, PHP 7.0.14-2+deb.sury.org

xenial+1
but with Response class

Cannot declare class SymfonyComponentHttpFoundationResponse, because the name is already in use in /var/www/var/cache/prod/classes.php on line 4479

In prod environment it seems to appear when using the HttpCache with AppCache().

Well, I found this issue with the use of FOSHttpCacheBundle FriendsOfSymfony/FOSHttpCacheBundle#276

afair this is because of a hard to reproduce bug in opcache try completely disabling it.

@thi3rry your issue is different and should be solved by #21184
@RubenHarms can we close this issue then?

Closing due to no response.

@RubenHarms feel free to come back with more details and we’ll re-open.

I got the same issue with SymfonyComponentConfigConfigCacheInterface

Источник

Cannot declare class because the name is already in use #374

Following the tutorial, as it is, for a project I am working on gave ‘class not found exception’ in:

  1. configuring the ApplicationAspectKernel in the front controller,
  2. registering aspect in aspect kernel, and
  3. declaring pointcut in an aspect for the methods of some class

To solve this, I added include statements:

  1. include ‘../application/ApplicationAspectKernel.php’; for my project’s front controller
  2. include ‘aspect/MonitorAspect.php’; in ApplicationAspectController.php
  3. include ‘../application/controller/CallbackController.php’; in MonitorAspect.php (CallbackController is the class whose methods I want to intercept).

On doing this I get the error PHP Fatal error: Cannot declare class CallbackController, because the name is already in use in /var/www/html/vyom-crm-frontend/application/controller/CallbackController.php on line 0

[Edit]: I removed the third include above. This resolved the above error. Now, the interceptor didn’t work with the following pointcut

This pointcut works — @Before(«execution(public **->*(*))»)
But I don’t want to intercept all methods of all classes. There is a specific method in CallbackController that I want to intercept.

Please help me solve this. Thanks!

The text was updated successfully, but these errors were encountered:

It seams that you are not using Composer (https://getcomposer.org) for auto loading classes?

In order for Go! AOP to work properly, usage of Composer as class autoloader is u must.

@TheCelavi I am using Composer. Code in my index.php —

Hi, your init section looks invalid. Where is your appDir setting? And you should always configure the cacheDir option in order to have good performance.

You should also remove first include for ApplicationAspectKernel.php and additional check for class existence.

Could you also show the namespace of your CallbackController ? And please, report your version of framework too.

@lisachenko
your init section looks invalid. Where is your appDir setting — Couldn’t follow what you mean. Which part are you calling the ‘init section’ and which settings are appDir settings?

You should also remove first include for ApplicationAspectKernel.php and additional check for class existence. — that gives class not found exceptions.

Could you also show the namespace of your CallbackController — It has no declared namespace.

report your version of framework — ^2.1

appDir — (sorry, not documented setting, will be fixed with new documentation) a path which points to a rood folder of your project/application source. includePaths is optional and should point to additional directories where your source code residue (or at least, code which should be weaved.). If you are familiar with Symfony — you may see Go! AOP Symfony bundle for reference.

You should also remove first include for ApplicationAspectKernel.php and additional check for class existence. — that gives class not found exceptions.

If you are getting «class not found» exception when loading your class — that means that Composer is not all setup properly to load your classes.

In general, if Composer is setup properly (and you are using Composer for class autoloading) — beside «require ‘../vendor/autoload.php’;» you should not have any need to use require , include and so on. for class loading in your project, except, of course, in your app entry script (e.g. index.php)

If you are getting «Cannot declare class CallbackController, because the name is already in use» that simply means what it said — CallbackController is being loaded twice. It is going to be hard to give you any more info if there is no full insight in application code (at least for me, maybe Alexandar would have more luck).

Источник

Ошибка Cannot declare class

Цитата
Федор Михайлов написал:
Может быть есть другие советы
Цитата
Павел Петриенко написал:
если судить по аналогии с файлами element.php & elementtable.php
Цитата
Антон Егоров написал:
Если это особенность обновления, то может быть это нужно задокументировать, с пометкой «после обновления удалите вручную такой-то файл».

Здравствуйте. У меня возникла похожая проблема но с компонентом меню.

Несколько лет назад была сделана копия этого компонента для кастомизации в папку «/bitrix/components/user/menu/», которая и использовалась. При этом платформа периодически обновлялась. Однако несколько месяцев назад было решено подключить меню из папки «/bitrix/components/bitrix/menu/», что вызвало следующую ошибку:

Цитата
Olgert написал:
Подскажите пожалуйста как исправить эту проблемму?
Цитата
Olgert написал:
Подскажите пожалуйста как исправить эту проблемму?

Либо не использовать оба компонента одновременно, либо (что самое правильное и так нужно было сделать изначально) переименовать класс в кастомизированном компоненте.

Спасибо!
Действительно оказалось что на странице использовалось еще одно меню из папки «/bitrix/components/user/menu/». И когда я переподключил нужное меню из папки «bitrix» второе осталось подключенным из папки «user» и это вызвало ошибку. Спасибо буду знать.

З.Ы. Если что наш сайт не коммерческий и поддерживается полупрофессионалом.

В моем случае были ошибка «Cannot declare class BitrixIblockElementTable, because the name is already in use», при этом страница открывалась в браузере, но выдавала ошибку 500. Данную ошибку вызывал типовой компонент «Просмотренные товары».

Источник

Cannot declare class m140209_132017_init, because the name is already in use #13989

What steps will reproduce the problem?

What is the expected result?

What do you get instead?

Additional info

Q A
Yii version yiisoft/yii2 dev-master 03e0607 Yii PHP Framework Version 2
PHP version PHP 7.1.3 (cli) (built: Mar 17 2017 22:24:22) ( NTS )
Operating system Debian

The text was updated successfully, but these errors were encountered:

do you have an other migration with that name?

I find problem
no set namespace in the migration file
new feature so new

After I put namespace into a migration class file
I still can do apply the migration without config

Note: migrations specified via [[yiiconsolecontrollersMigrateController::migrationPath|migrationPath]] can not contain a namespace, namespaced migration can be applied only via [[yiiconsolecontrollersMigrateController::migrationNamespaces]] property.

We will add namespaces to migrations
#13918

The migration with namespace still work in the old project (i.e. module migration)?

I’m not sure that I’ve got your question.

Current schema (not ideal):
Apply migration in project without namespace ./yii migrate/up
Apply migration from vendor module without namespace ./yii migrate/up —migrationPath=@yii/rbac/migrations/

Module have update, migration have namespace now. Project not modified.

BC: Migration in module must still work with old syntax. (Autoload must use any of both method)

Could you re-post this message to #13918 and we will continue discussion there?

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

samyak45 opened this issue

Dec 8, 2017

· 24 comments

Comments

@samyak45

Following the tutorial, as it is, for a project I am working on gave ‘class not found exception’ in:

  1. configuring the ApplicationAspectKernel in the front controller,
  2. registering aspect in aspect kernel, and
  3. declaring pointcut in an aspect for the methods of some class

To solve this, I added include statements:

  1. include ‘../application/ApplicationAspectKernel.php’; for my project’s front controller
  2. include ‘aspect/MonitorAspect.php’; in ApplicationAspectController.php
  3. include ‘../application/controller/CallbackController.php’; in MonitorAspect.php (CallbackController is the class whose methods I want to intercept).

On doing this I get the error PHP Fatal error: Cannot declare class CallbackController, because the name is already in use in /var/www/html/vyom-crm-frontend/application/controller/CallbackController.php on line 0

[Edit]: I removed the third include above. This resolved the above error. Now, the interceptor didn’t work with the following pointcut

@Before("execution(public CallbackController->*(*))")

This pointcut works — @Before("execution(public **->*(*))")
But I don’t want to intercept all methods of all classes. There is a specific method in CallbackController that I want to intercept.

Please help me solve this. Thanks!

@TheCelavi

It seams that you are not using Composer (https://getcomposer.org) for auto loading classes?

In order for Go! AOP to work properly, usage of Composer as class autoloader is u must.

@samyak45

@TheCelavi I am using Composer. Code in my index.php —

<?php


// Auto-loading the classes (currently only from application/libs) via Composer's PSR-4 autoloader
// Later it might be useful to use a namespace here, but for now let's keep it as simple as possible
require '../vendor/autoload.php';

include_once '../application/ApplicationAspectKernel.php';

if(class_exists('ApplicationAspectKernel')) {
// Initialize an application aspect container
    $applicationAspectKernel = ApplicationAspectKernel::getInstance();
    $applicationAspectKernel->init(array(
        'debug' => true, // use 'false' for production mode
        // Cache directory
        'cacheDir' => null,
        // Include paths restricts the directories where aspects should be applied, or empty for all source files
        'includePaths' => array(
            __DIR__.'/../application/'
        )
    ));
}
else {
    error_log("class ApplicationAspectKernel not found");
}

// Start our application
new Application();

?>

@lisachenko

Hi, your init section looks invalid. Where is your appDir setting? And you should always configure the cacheDir option in order to have good performance.

You should also remove first include for ApplicationAspectKernel.php and additional check for class existence.

Could you also show the namespace of your CallbackController? And please, report your version of framework too.

@samyak45

@lisachenko
your init section looks invalid. Where is your appDir setting — Couldn’t follow what you mean. Which part are you calling the ‘init section’ and which settings are appDir settings?

You should also remove first include for ApplicationAspectKernel.php and additional check for class existence. — that gives class not found exceptions.

Could you also show the namespace of your CallbackController — It has no declared namespace.

report your version of framework — ^2.1

@TheCelavi

appDir — (sorry, not documented setting, will be fixed with new documentation) a path which points to a rood folder of your project/application source. includePaths is optional and should point to additional directories where your source code residue (or at least, code which should be weaved.). If you are familiar with Symfony — you may see Go! AOP Symfony bundle for reference.

You should also remove first include for ApplicationAspectKernel.php and additional check for class existence. — that gives class not found exceptions.

If you are getting «class not found» exception when loading your class — that means that Composer is not all setup properly to load your classes.

In general, if Composer is setup properly (and you are using Composer for class autoloading) — beside «require ‘../vendor/autoload.php’;» you should not have any need to use require, include and so on… for class loading in your project, except, of course, in your app entry script (e.g. index.php)

If you are getting «Cannot declare class CallbackController, because the name is already in use» that simply means what it said — CallbackController is being loaded twice. It is going to be hard to give you any more info if there is no full insight in application code (at least for me, maybe Alexandar would have more luck).

@samyak45

@TheCelavi parts of the application code that might be helpful —
index.php

<?php

require '../vendor/autoload.php';

$applicationAspectKernel = ApplicationAspectKernel::getInstance();
$applicationAspectKernel->init(array(
    'debug' => true, // use 'false' for production mode
    // Cache directory
    'appDir' => '../application/',
    'cacheDir' => null,
    // Include paths restricts the directories where aspects should be applied, or empty for all source files
    'includePaths' => array(
        '../application/'
    )
));
// Start our application
new Application();

composer.json

{
    "name": "Inventory",
    "type": "project",
    "description": "Inventory",
    "keywords": ["mvc"],
    "homepage": "https://rightklick.in/",
    "license": "MIT",
    "require-dev": {
        "php": ">=5.5.0"
    },
    "autoload": {
        "psr-4": { "": ["application/core/", "application/model/"] }
    },
    "require": {
        "goaop/framework": "^2.1"
    }
}

autoload.php

<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit4dad9c0cc8cbc9a8baecb2ef83f1193c::getLoader();

autoload_real.php

<?php

// autoload_real.php @generated by Composer

class ComposerAutoloaderInit4dad9c0cc8cbc9a8baecb2ef83f1193c
{
    private static $loader;

    public static function loadClassLoader($class)
    {
        if ('ComposerAutoloadClassLoader' === $class) {
            require __DIR__ . '/ClassLoader.php';
        }
    }

    public static function getLoader()
    {
        if (null !== self::$loader) {
            return self::$loader;
        }

        spl_autoload_register(array('ComposerAutoloaderInit4dad9c0cc8cbc9a8baecb2ef83f1193c', 'loadClassLoader'), true, true);
        self::$loader = $loader = new ComposerAutoloadClassLoader();
        spl_autoload_unregister(array('ComposerAutoloaderInit4dad9c0cc8cbc9a8baecb2ef83f1193c', 'loadClassLoader'));

        $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
        if ($useStaticLoader) {
            require_once __DIR__ . '/autoload_static.php';

            call_user_func(ComposerAutoloadComposerStaticInit4dad9c0cc8cbc9a8baecb2ef83f1193c::getInitializer($loader));
        } else {
            $map = require __DIR__ . '/autoload_namespaces.php';
            foreach ($map as $namespace => $path) {
                $loader->set($namespace, $path);
            }

            $map = require __DIR__ . '/autoload_psr4.php';
            foreach ($map as $namespace => $path) {
                $loader->setPsr4($namespace, $path);
            }

            $classMap = require __DIR__ . '/autoload_classmap.php';
            if ($classMap) {
                $loader->addClassMap($classMap);
            }
        }

        $loader->register(true);

        if ($useStaticLoader) {
            $includeFiles = ComposerAutoloadComposerStaticInit4dad9c0cc8cbc9a8baecb2ef83f1193c::$files;
        } else {
            $includeFiles = require __DIR__ . '/autoload_files.php';
        }
        foreach ($includeFiles as $fileIdentifier => $file) {
            composerRequire4dad9c0cc8cbc9a8baecb2ef83f1193c($fileIdentifier, $file);
        }

        return $loader;
    }
}

function composerRequire4dad9c0cc8cbc9a8baecb2ef83f1193c($fileIdentifier, $file)
{
    if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
        require $file;

        $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
    }
}

@samyak45

@TheCelavi @lisachenko does the above part of the application code help understanding what am I doing wrong?

@lisachenko

Hi, only missing option is cacheDir right now, strange that it still works for you, because there should be an exception. All other settings look ok…

@samyak45

@lisachenko but I am still not being able to define pointCut specific for the class/method I want to intercept.

This works — @Before("execution(public **->*(*))")
This doesn’t — @Before("execution(public CallbackController->*(*))")

@samyak45

@lisachenko I am still having to use include_once '../application/ApplicationAspectKernel.php'; without it the error PHP Fatal error: Uncaught Error: Class 'ApplicationAspectKernel' not found still comes.

@lisachenko

I am still having to use include_once ‘../application/ApplicationAspectKernel.php’;

This is because your configuration for PSR-4 is incorrect:

    "autoload": {
        "psr-4": { "": ["application/core/", "application/model/"] }
    },

Please, add "application/" directory to this list or move this ApplicationAspectKernel.php file into your core directory, so composer will be able to find it.

@lisachenko

This doesn’t — @before(«execution(public CallbackController->())»)

Please, give me full path and content of this CallbackController file (without method bodies), including the namespaces, uses, includes, etc. And several methods (only names, without bodies).

@samyak45

class not found errors resolved. For the pointcut part:

give me full path and content of this CallbackController file (without method bodies), including the namespaces, uses, includes, etc. And several methods (only names, without bodies).

full path — <project_folder>/application/controller/CallbackController.php

namespace — none (no namespaces have been used in the controllers and models of this project)

includes — none

extends — Controller

methods — foo() (there is only one method apart from the constructor.)

@lisachenko

PHP Fatal error: Uncaught Error: Class ‘aspectMonitorAspect’ not found

It’s the same, you have not configured autoload section in your composer.json file. Just move to application/core directory or adjust your composer.json file. Also, remove aspect namespace in this file — you should either configure autoloader or clean it if you move it into the application/core directory. After that aspect will be registered and AOP should apply to your files.

From what I can see, all troubles in this issue are because of wrong composer configuration/autoloading initialization.

@samyak45

@lisachenko the class not found errors were resolved. (As I said in my previous comment). The pointcut issue remains.

@samyak45

To attempt to solve the pointcut issue I, —

  1. Added namespace controllercallback to CallbackController.php.
  2. Since CallbackController extends Controller, added namespace corecontroller to Controller.php containing the parent class Controller, and added use corecontrollerController; to CallbackController.php
  3. Added a use controllercallback; statement to MonitorAspect.php

This gave new errors: PHP Fatal error: Class ‘Controller’ not found. (Class Controller is in application/core should be auto included.

@lisachenko my composer autoload settings now are —

"autoload": {
        "psr-4": { "": ["application/core/", "application/model/", "application/controller/", "application/aspect/"] }
    },

Also I have successfully run composer update after changing conposer.json (this is what resolved class not found on MonitorAspect).

@lisachenko

@samyak45 Please, resolve all class «xxx» not found errors before asking about help, as I’m sure that it’s simple incorrect configuration of composer. If you have troubles in configuring composer loader, then I would recommend you not to use AOP for a while, because knowing PSR-0,4 standards is must have.

To debug all class XXX not found, just create new instances of them right after include of autoload file.

require '../vendor/autoload.php';

You should be able to create instance of aspect kernel, aspect instance, your controller instance.
After that we can check why it’s not working for you.

@samyak45

@lisachenko is using namespaces necessary to use goaop?
This works without having to use namespaces in my project @Before("execution(public **->*(*))")
But @Before("execution(public CallbackController->*(*))") doesn’t work for functions inside controller. (Though it does work for the constructors of controller classes.)

Also, I am being able to intercept methods of CallbackModel used by CallbackController using @Before("execution(public CallbackModel::*(*))"). However, I want to intercept at controller level.

@lisachenko

@lisachenko is using namespaces necessary to use goaop?

No it isn’t necessary, engine can work with global namespace too.

Just for fun, try to use @Before("execution(public ***Contr*->*(*))") Who knows…
In order to find out what is the root cause you should debug why pointcut isn’t matched for your class.

You have definitely some typo somewhere: in classname or in the pointcut…

PS: I’m right that methods in your controller are not final?

@samyak45

Just for fun, try to use @before(«execution(public **Contr->())») Who knows.

Doesn’t work.

You have definitely some typo somewhere: in classname or in the pointcut…

No. I have rechecked. Have also got other members of my team to review but no luck.

I’m right that methods in your controller are not final

No. They are not.

One thing though — the controllers in my project convert to url by the logic — all controller classes must end with the string ‘Controller’. When hitting any controller named Controller, you don’t need to put ‘Controller’ in the url, just ‘<base_url>/x/<controller_method> works.

Does above information help?

PS: Using @Before("execution(public **->*(*))") intercepts the controller constructor but no other methods.

@lisachenko

@samyak45 have no idea what is wrong :( Description of your issue is pretty simple, but in order to check what is wrong, I need to debug it right on your instance.

I have tried to reproduce you case:

  1. composer create-project goaop/framework
  2. Created demos/controller directory and put CallbackController.php file with following content:
<?php

class CallbackController
{
    public function testHello()
    {
        echo "yay!";
    }
}
  1. In the autoload_aspect.php file I’ve added
$controller = new CallbackController();
$controller->testHello();
  1. Changed LoggingAspect pointcut to the @Before("execution(public CallbackController->*(*))") (I’m using Go! AOP Framework plugin with PhpStorm, so I can see A⬇️ icon in the gutter)
  2. Added into composer.json section for loading my controller from demos/controller directory:
        "psr-4": {
            "": "demos/controller/"
         }
  1. Warmed composer (in order to generate autoload files)
  2. Refreshed my page — and everything works:
Calling Before Interceptor for execution(CallbackController->testHello()) with arguments: []
yay!

@lisachenko

@samyak45

@lisachenko no I couldn’t solve it so to get my work done for now I added a new function to my CallbackModel, that now does all that happened in CallbackController function I wanted to intercept. And I added interceptor for this function in the model. Architecturally this isn’t right but was compelled to use this hack to get work done.

Thanks. You can now close this issue.

@lisachenko

Ok, wish you good luck.

Ping me if some help will be required.

 

Пользователь 1214851

Заглянувший

Сообщений: 44
Баллов: 2
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 16.06.2017

При открытии существующей задачи, появляется ошибка
Fatal error:  Cannot declare class BitrixTasksTaskTable, because the name is already in use in /home/bitrix/www/bitrix/modules/tasks/lib/task.php on line 0
Подскажите, где копать.

 

Александр Новокшанов, а можете полный текст ошибки со стек-трейсом?
Какая версия битрикс24?

 

Пользователь 1214851

Заглянувший

Сообщений: 44
Баллов: 2
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 16.06.2017

Обновлял битрикс 19-го числа. Это все, что  выводится на экран.

 

Пользователь 1890127

Эксперт

Сообщений: 400
Баллов: 68
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 28.03.2018

#4

0

08.02.2019 06:15:04

Цитата
Александр Новокшанов написал:

Fatal error:  Cannot declare class BitrixTasksTaskTable, because the name is already in use in /home/bitrix/www/bitrix/modules/tasks/lib/task.php on line 0
Подскажите, где копать.

Не решили проблему?

У нас то же самое сообщение стало появляться

 

Пользователь 136059

Гуру

Сообщений: 5418
Баллов: 636
Авторитет:

22

Рейтинг пользователя:

0

Регистрация: 16.07.2012

#5

0

08.02.2019 10:06:10

Цитата
Роман написал:
У нас то же самое сообщение стало появляться

Обратитесь с тех.поддержку, видимо при обновлении битрикс некорректно обновил технические файлы

Голосуй за идеи по развитию API Bitrix:
https://idea.1c-bitrix.ru/26707/
https://idea.1c-bitrix.ru/26709/
https://idea.1c-bitrix.ru/the-local-extension-folder-js/

 

Пользователь 291336

Эксперт

Сообщений: 1497
Баллов: 244
Авторитет:

31

Рейтинг пользователя:

4

Регистрация: 08.11.2014

#6

0

01.10.2019 11:29:08

Цитата
Fatal error:  Cannot declare class BitrixIblockPropertyTable, because the name is already in use in /var/www/SOMESITE/bitrix/modules/iblock/lib/property.php on line 0

такая же проблема — 1С-Битрикс: Управление сайтом 19.0.293

обновление bitrix поможет?

Как создать лендинг из любого готового решения Bitrix

 

Евгений Жуков

Администратор

Сообщений: 9035
Баллов: 1747
Авторитет:

8

Рейтинг пользователя:

39

Регистрация: 05.08.2005

Epic fail — сказать «это так просто» и не суметь сделать

#7

2

01.10.2019 12:17:41

Цитата
Роман Семёнов написал:
такая же проблема

Не такая же — у топик-стартера модуль задач, у вас — инфоблоки.

Вариантов два — либо некорректно встало обновление iblock 18.6.700 (апдейтер не смог удалить файл iblock/lib/property.php, например, из-за прав), либо после установки перезаливались файлы модуля.

Цитата
Роман Семёнов написал:
обновление bitrix поможет?

Нет. Вручную удалите файл iblock/lib/property.php, предварительно проверив, что существует iblock/lib/propertytable.php. А лучше обратитесь в ТП, дав административный доступ.

Не надо сверлить зубы через задний проход дрелью от Сваровски

 

Пользователь 1242451

Заглянувший

Сообщений: 13
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 30.06.2017

#8

0

12.10.2019 22:36:41

Цитата
Евгений Жуков написал:
Нет. Вручную удалите файл iblock/lib/property.php, предварительно проверив, что существует iblock/lib/propertytable.php. А лучше обратитесь в ТП, дав административный доступ.

Спасибо, добрый человек)

 

Пользователь 620445

Заглянувший

Сообщений: 9
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 04.07.2016

Такая ошибка возникает при попытке установить два одинаковых модуля. Можно проверить разместив модуль в директории /loca/modules/ два раза. Даже без установки будет ошибка.

 

Пользователь 113306

Заглянувший

Сообщений: 7
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 13.01.2012

#10

2

25.10.2019 19:29:12

Добрый вечер, та же проблема с bitrix/modules/iblock/lib/element.php, bitrix/modules/iblock/lib/elementtable.php

Цитата
Цитата
Роман Семёнов  написал:
обновление bitrix поможет?

Нет. Вручную удалите файл iblock/lib/property.php, предварительно проверив, что существует iblock/lib/propertytable.php. А лучше обратитесь в ТП, дав административный доступ.

удаление первого помогло и функционал заработал. Но пока только на дев площадке сделал. Вопрос, могу ли быть уверенным, что функционал в других частях сайта не посыпется?

 

Евгений Жуков

Администратор

Сообщений: 9035
Баллов: 1747
Авторитет:

8

Рейтинг пользователя:

39

Регистрация: 05.08.2005

Epic fail — сказать «это так просто» и не суметь сделать

#11

0

25.10.2019 19:34:56

Цитата
Василий Данилов написал:
Вопрос, могу ли быть уверенным, что функционал в других частях сайта не посыпется?

Конкретизируйте вопрос.

Цитата
Василий Данилов написал:
Добрый вечер, та же проблема с bitrix/modules/iblock/lib/element.php, bitrix/modules/iblock/lib/elementtable.php

И по-прежнему ни одного обращения в ТП для попытки выяснения сценария.

Не надо сверлить зубы через задний проход дрелью от Сваровски

 

Пользователь 12233

Заглянувший

Сообщений: 23
Баллов: 2
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 26.05.2007

#12

0

06.11.2019 04:50:40

Тикет 2502140

Если с «Cannot declare class BitrixIblockPropertyTable»

удалось разобраться

, то теперь ещё и «Cannot declare class BitrixIblockIblockTable» вылезло при попытке создания фасетного индекса в админке

 

Администратор

Сообщений: 9035
Баллов: 1747
Авторитет:

8

Рейтинг пользователя:

39

Регистрация: 05.08.2005

Epic fail — сказать «это так просто» и не суметь сделать

#13

1

06.11.2019 10:49:07

Внимание! Настоятельно рекомендую всем, кто сталкивается с такой проблемой, проверить права доступа на папку /bitrix/modules/.

Василий Зайковский, проблема та же самая. Убедитесь, что есть файл /bitrix/modules/iblock/lib/iblocktable.php и удалите /bitrix/modules/iblock/lib/iblock.php. Либо переустановите обновление, убедившись, что с правами доступа все в порядке.

Не надо сверлить зубы через задний проход дрелью от Сваровски

 

Пользователь 12233

Заглянувший

Сообщений: 23
Баллов: 2
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 26.05.2007

#14

0

06.11.2019 12:26:27

Да. Всё OK. Помогло! Благодарю!

P.S. При полной проверке сообщение «Все проверенные файлы и папки доступны для чтения и записи»

 

Евгений Жуков

Администратор

Сообщений: 9035
Баллов: 1747
Авторитет:

8

Рейтинг пользователя:

39

Регистрация: 05.08.2005

Epic fail — сказать «это так просто» и не суметь сделать

#15

0

06.11.2019 12:35:20

Цитата
Василий Зайковский написал:
Да. Всё OK. Помогло! Благодарю!

Я рад.

Не надо сверлить зубы через задний проход дрелью от Сваровски

 

Пользователь 1288159

Заглянувший

Сообщений: 32
Баллов: 2
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 17.04.2019

#16

1

23.06.2020 17:19:29

Цитата
Евгений Жуков написал:
Внимание!  Настоятельно рекомендую всем, кто сталкивается с такой проблемой, проверить права доступа на папку /bitrix/modules/.

Василий Зайковский , проблема та же самая. Убедитесь, что есть файл /bitrix/modules/iblock/lib/iblocktable.php и удалите /bitrix/modules/iblock/lib/iblock.php. Либо переустановите обновление, убедившись, что с правами доступа все в порядке.

Евгений, а всего навсего нужно выводить ошибку при обнове и отдавать сhangelog администратору что отработало успешно а где затык был. Видимо разработчики битрикса не слышали о таком слове в написание программы как «исключения», не удалось удалить файл, прав не хватило — выведи пользователю сообщение, а не тихо мирно забей. Это признак *** кода.!

Научите ваших мастеров писать нормально и пользоваться

https://www.php.net/manual/ru/language.exceptions.php

У нас таких проблем было несколько практически на свежеустановленом портале ему 2 месяца, права никто не менял и все корректные на всю папку bitrix, но гадость случается и теперь вопрос А КОРРЕКТНО ЛИ ВСЕ ОБНОВЫ ВСТАЛИ? я не могу быть уверенным, а вдруг какой метод не отработал при установке и bitrix умолчал! Ваша поддержка одна из наискорейших, день они могут выяснять стоят ли обновы, второй подключают и передают специалисту, через 2 дня он просит доступ еще через день он начинает в лучшем случае смотреть, и только через неделю от задания вопроса мы получаем ответ.

А теперь опять вопрос? как нам неделю работать? На карантин уходить? по причине того что Битрикс24 заболел? Может Битрикс будет оплачивать з/п сотрудникам потому, что у них продукт кривой?

 

Пользователь 4529832

Заглянувший

Сообщений: 7
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 17.09.2020

#17

0

17.09.2020 14:22:49

Здравствуйте.

После обновления Битрикс (до «1С-Битрикс: Управление сайтом 20.0.1700») на все страницах интернет-магазина появилось следующее сообщение:
Fatal error: Cannot declare class BitrixIblockElementTable, because the name is already in use in /home/c/ct48436/mamontenok/public_html/bitrix/modules/iblock­/lib/element.php on line 347

Честно говоря, мне не понятно с чем это связано. Ознакомился с сообщениями в этом разделе форума по теме «Ошибка Cannot declare class». Если я правильно понял, то в папке public_html/bitrix/modules/iblock/lib нужно удалить/переименовать три файла: element.php, iblock.php, property.php.

В папке public_html/bitrix/modules/iblock/lib переименовал три файла: element.php, iblock.php, property.php. Помогло! Вышеуказанное сообщение пропало и, по-моему, интернет-магазин работает нормально.

ВОПРОС:
Правильными ли были мои действия относительно удаления/переименования следующих файлов: element.php, iblock.php, property.php?

P.S
Права на чтение и запись в папку /bitrix/modules/, а так же на файлы были нормальные.

 

Евгений Жуков

Администратор

Сообщений: 9035
Баллов: 1747
Авторитет:

8

Рейтинг пользователя:

39

Регистрация: 05.08.2005

Epic fail — сказать «это так просто» и не суметь сделать

#18

0

17.09.2020 17:25:59

Цитата
Андрей Алексеев написал:
В папке public_html/bitrix/modules/iblock/lib переименовал три файла: element.php, iblock.php, property.php. Помогло! Вышеуказанное сообщение пропало и, по-моему, интернет-магазин работает нормально.

Эм… А можно поподробней? Есть подозрение, что не совсем правильно.

Не надо сверлить зубы через задний проход дрелью от Сваровски

 

Пользователь 247941

Постоянный посетитель

Сообщений: 64
Баллов: 10
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 16.03.2014

#19

0

16.10.2020 14:52:48

Евгений, здравствуйте

Цитата
Евгений Жуков написал:
Либо переустановите обновление, убедившись, что с правами доступа все в порядке.

Не подскажете как можно переустановить обновления?

 

Пользователь 163998

Заглянувший

Сообщений: 1
Баллов: 1
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 19.06.2013

#20

0

12.11.2020 09:03:14

 

Цитата
Евгений Жуков написал:

Эм… А можно поподробней? Есть подозрение, что не совсем правильно.

Совсем неправильно. Только что потоптался по этим граблям. Два проекта оч давно не обновлялись, пару лет точно. И после обновления в /bitrix/modules/iblock/lib/ обнаружились два файла, объявляющих один и тот же класс. Это были упомянутые выше element.php & elementtable.php, в обоих один и тот же класс

Код
class ElementTable extends ORMDataDataManager 

Заглянув в свежеустановленный БУС, увидел, что там нет elementtable.php, а есть только  element.php. Поэтому переименовал elementtable.php в elementtable.php.bad

Сами файлы практически идентичны:

Код
diff element.php elementtable.php.bad
3a4,6
> use BitrixIblockORMElementV1Entity;
> use BitrixIblockORMElementV2Entity;
> use BitrixIblockORMQuery;
6a10
> use BitrixMainORMFieldsRelationsManyToMany;
48,49c52,53
<  * <li> PREVIEW_PICTURE_FILE reference to {@link BitrixFileFileTable}
<  * <li> DETAIL_PICTURE_FILE reference to {@link BitrixFileFileTable}
---
>  * <li> PREVIEW_PICTURE_FILE reference to {@link BitrixMainFileTable}
>  * <li> DETAIL_PICTURE_FILE reference to {@link BitrixMainFileTable}
53,55c57,59
<  * <li> MODIFIED_BY_USER reference to {@link BitrixUserUserTable}
<  * <li> CREATED_BY_USER reference to {@link BitrixUserUserTable}
<  * <li> WF_LOCKED_BY_USER reference to {@link BitrixUserUserTable}
---
>  * <li> MODIFIED_BY_USER reference to {@link BitrixMainUserTable}
>  * <li> CREATED_BY_USER reference to {@link BitrixMainUserTable}
>  * <li> WF_LOCKED_BY_USER reference to {@link BitrixMainUserTable}

Что касается вопроса

Цитата
Андрей Алексеев написал:
ВОПРОС:Правильными ли были мои действия относительно удаления/переименования следующих файлов: element.php, iblock.php, property.php?

то однозанчно НЕПРАВИЛЬНО, так как в имеющихся казалось бы тоже дублирующих (если судить по аналогии с файлами  element.php & elementtable.php) парах iblock.php/ibloctable.php и property.php/propertytable.php находятся РАЗНЫЕ классы. Впрочем, Вы наверное уже сами убедились, что это непрвильно, пишу для того. чтобы другие нашедшие тему так не поступали.

ЗЫ. Евгений Жуков, права однозначно не при чем, на обоих проектах все права были и есть в порядке, проверялись перед обновлением.

 

Евгений Жуков

Администратор

Сообщений: 9035
Баллов: 1747
Авторитет:

8

Рейтинг пользователя:

39

Регистрация: 05.08.2005

Epic fail — сказать «это так просто» и не суметь сделать

#21

0

12.11.2020 12:51:36

Цитата
Павел Петриенко написал:
Заглянув в свежеустановленный БУС, увидел, что там нет elementtable.php, а есть только  element.php. Поэтому переименовал elementtable.php в elementtable.php.bad

Вы сделали ровно наоборот. Откуда брали дистрибутив и версия iblock в нем?

Не надо сверлить зубы через задний проход дрелью от Сваровски

 

Пользователь 247941

Постоянный посетитель

Сообщений: 64
Баллов: 10
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 16.03.2014

#22

0

12.11.2020 13:23:40

Цитата
Евгений Жуков написал:
Вы сделали ровно наоборот. Откуда брали дистрибутив и версия iblock в нем?

У меня тоже проблема ушла после устранения этого «наоборот»

 

Пользователь 520591

Посетитель

Сообщений: 56
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 11.03.2016

#23

0

17.12.2020 00:09:17

При обновлении вылезла вот такая ошибка:

Fatal error: Cannot declare class Landing, because the name is already in use in  /bitrix/updates/update_mxxxxxxxx/landing/install/index.php on line 727

Подскажите как побороть

 

Евгений Жуков

Администратор

Сообщений: 9035
Баллов: 1747
Авторитет:

8

Рейтинг пользователя:

39

Регистрация: 05.08.2005

Epic fail — сказать «это так просто» и не суметь сделать

#24

1

17.12.2020 11:46:38

Цитата
Федор Михайлов написал:
Подскажите как побороть

Обратиться в ТП с доступом.

Не надо сверлить зубы через задний проход дрелью от Сваровски

 

Пользователь 520591

Посетитель

Сообщений: 56
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 11.03.2016

#25

0

17.12.2020 13:52:58

Цитата
Евгений Жуков написал:

Цитата
Федор Михайлов  написал:
Подскажите как побороть

Обратиться в ТП с доступом.

Спасибо за отклик, но мы не ищем лёгких путей :) Может быть есть другие советы?

Today I received the same-type error:

PHP Fatal error: Cannot declare class ClassNameHere , because the name is already in use in /var/www/m2/magento2/app/code/path/to/the/class.php on line 100

where the line 100 is end of the file.

Approximately after 4 hours of debugging I really find the reason: a misprint in the namespace declaration. Till the final moment I didn’t believe that it is a typographical error in names declaration, but when I have rewritten all names anew — the mistake has disappeared. This article was very helpful:

I’ll scratch my head for a while, wonder what’s going on, and
eventually realize it’s this

Pulsetorm

i.e. I’ve mistyped a namespace name, and when the initial autoloads
loads the class file, it won’t have defined the class it’s looking
for, and then a second autoloader (Composer’s usually) loads it again,
and tries to redefine the same incorrect class.

i.e., Magento wanted the class

PulsestormHelloworldObserversBlock

but I defined

PulsetormHelloworldObserversBlock

thanks to the wrong namespace.

Thank you, Alan Storm :)

UPDATE:

Another type of that error is incorrect Namespace declaration with missing part of the namespace, as in this example:

Error:

Repositories code generation… 1/7 [====>————————]
14% 1 sec 50.0 MiBPHP Fatal error: Cannot declare class
MigrationStepVersion11410to2000Test, because the name is already in
use in
/var/www/vhosts/rwld/vendor/magento/data-migration-tool/tests/unit/testsuite/Migration/Step/UrlRewrite/Version11410to2000Test.php
on line 109

where the line 109 is end of the file.

In the file vendor/magento/data-migration-tool/tests/unit/testsuite/Migration/Step/UrlRewrite/Version11410to2000Test.php we found the namespace as MigrationStep when the correct namespace should be MigrationStepUrlRewrite because path to this class is Migration/Step/UrlRewrite. After changing of the namespace to Migration/Step/UrlRewrite the error is gone.

This is an error happened upon executing a command for processing migration script file. The concept itself, the migration script file processing is a concept or not only just a concept but also the implementation offered in Laravel web-based application development to operate with tables represented by each of the migration script file. The file itself is not specified since the process of executing the migration script files are done by executing all of the migration script files located normally in folder ‘/database/migrations’.

All of the migration script files can be executed by typing the following command in the bash prompt :

php artisan migrate:refresh

Below is the output of the above command execution :

user@hostname:/var/www/html/laravel$ php artisan migrate:refresh
PHP Fatal error: Cannot declare class CreateCategoriesTable, because the name is already in use in /var/www/html/laravel-support-ticket/database/migrations/2017_11_02_151257_create_categories_table.php on line 31

[SymfonyComponentDebugExceptionFatalErrorException]
Cannot declare class CreateCategoriesTable, because the name is already in use

user@hostname:/var/www/html/laravel$

In this article context, especially based on the above output generated by executing the commad php artisan migrate:refresh, the process cannot be proceed since it is actually generated an error message as shown in the above output. The error message is actually : “Cannot declare class CreateCategoriesTable, because the name is already in use”.

In the above context, “CreateCategoriesTable” is actually the name of the class specified in the migartion script file. It said that the class name has already exist because in the term of this case, there are three files which has the same name part which in the end there are three migration script files which have the same class name. Although those files are generated in the different time but it actually refers to the same class name. The situation is shown in the following :

user@hostname:/var/www/html/laravel/database/migrations$ ls -al
total 16
drwxrwxr-x 2 user     user 4096 Nov 5 22:08 .
drwxrwxr-x 3 www-data user 4096 Nov 5 22:22 ..
...
-rw-rw-r-- 1 www-data user 601 Nov 2 22:06 2017_11_02_150646_create_categories_table.php
-rw-rw-r-- 1 www-data user 601 Nov 2 22:12 2017_11_02_151257_create_categories_table.php
-rw-rw-r-- 1 www-data user 601 Nov 2 22:19 2017_11_02_151921_create_categories_table.php
...
user@hostname:/var/www/html/laravel/database/migrations$

In the context of this article, the solution which I implemented to solve the problem is by moving away the other files unnecessary. Since it can only be one script representing one class, just move the rest of the files into another location. I created one folder in the current path shown above and move the other two older files inside the folder. It is shown as follows :

user@hostname:/var/www/html/laravel/database/migrations$ mkdir temp
user@hostname:/var/www/html/laravel/database/migrations$

And move those files unrelated :

user@hostname:/var/www/html/laravel/database/migrations$ mv 2017_11_02_150646_create_categories_table.php 2017_11_02_151257_create_categories_table.php temp/
user@hostname:/var/www/html/laravel/database/migrations$ cd temp
user@hostname:/var/www/html/laravel/database/migrations$ ls -al 
total 16
drwxrwxr-x 2 user     user 4096 Nov 5 22:08 .
drwxrwxr-x 3 www-data user 4096 Nov 5 22:22 ..
-rw-rw-r-- 1 www-data user  601 Nov 2 22:06 2017_11_02_150646_create_categories_table.php
-rw-rw-r-- 1 www-data user  601 Nov 2 22:12 2017_11_02_151257_create_categories_table.php
user@hostname:/var/www/html/laravel/database/migrations/temp#

Summary: in this tutorial, you’ll learn about PHP namespaces, how to define classes that belong to a namespace, and how to use namespaces.

Why namespaces

When your project grows in complexity, you’ll need to integrate the code from others. Sooner or later, you’ll find that your code has different classes with the same name. This problem is known as name collision.

To resolve it, you can use namespaces. PHP supported namespaces since version 5.3.

What is a namespace

It’s easier to understand namespaces by analogy to the directory structure in a filesystem.

A directory stores related files, which is similar to a namespace that groups related classes.

A directory doesn’t allow you to have two files with the same name. However, you can have files with the same names in different directories. Likewise, namespaces mimic the same principle.

By definition, namespaces provide you with a way to group related classes and help you avoid any potential name collisions.

Namespaces are not limited to group classes. They can group other identifiers, including functions, constants, variables, etc.

Set up a directory structure

First, create a project directory, e.g., store and create a new index.php file in the directory.

Second, create src directory in the project directory and Model directory in the src directory.

Third, create a new file called Customer.php in the Model directory with the following code:

<?php class Customer { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } }

Code language: HTML, XML (xml)

The directory looks like the following:

. ├── index.php └── src └── Model └── Customer.php

Code language: plaintext (plaintext)

Define a namespace

To define a namespace, you place the namespace keyword followed by a name at the very top of the page. The following example gives the Customer class with a namespace StoreModel:

<?php namespace StoreModel; class Customer { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } }

Code language: HTML, XML (xml)
  • It’s customary to assign the src directory the Store namespace. And you can replace Store with your brand name, e.g., Apple.
  • It’s a good practice to imitate the directory structure with the namespace to find classes more easily. For example, every class within the directory will get the namespace StoreModel.

Use a class that belongs to a namespace

To use a class that belongs to a namespace in the index.php, you need to include the file and use the class:

<?php require 'src/Model/Customer.php'; $customer = new Customer('Bob'); echo $customer->getName();

Code language: HTML, XML (xml)

If you open the index.php, you’ll get a fatal error:

Fatal error: Uncaught Error: Class 'Customer' not found in...

Code language: JavaScript (javascript)

Since the Customer class now is namespaced, you need to use the fully qualified name that includes the namespace like this:

<?php require 'src/Model/Customer.php'; $customer = new StoreModelCustomer('Bob'); echo $customer->getName();

Code language: HTML, XML (xml)

Now, it should work properly.

Import a namespace

To avoid using the fully qualified names from a namespace, you can import the namespace with the use operator like this:

<?php require 'src/Model/Customer.php'; use StoreModel; $customer = new ModelCustomer('Bob'); echo $customer->getName();

Code language: HTML, XML (xml)

Now, you just need to prefix the class name with Model.

Import a class from a namespace

PHP allows you to import a class from a namespace instead of importing the namespace. For example:

<?php require 'src/Model/Customer.php'; use StoreModelCustomer; $customer = new Customer('Bob'); echo $customer->getName();

Code language: HTML, XML (xml)

In this example, we use the use operator to import the Customer class from the StoreModel namespace. Therefore, we don’t have to prefix the class name with the namespace.

Import multiple classes from a namespace

First, create a new file called Product.php in the src/Model directory:

<?php namespace StoreModel; class Product { }

Code language: HTML, XML (xml)

For demonstration purposes, the Product class is empty. Now, the directory structure looks like the following:

. ├── index.php └── src └── Model ├── Customer.php └── Product.php

Code language: plaintext (plaintext)

To use both Customer and Product classes from the index.php, you can import them individually like before:

<?php require 'src/Model/Customer.php'; require 'src/Model/Product.php'; use StoreModelCustomer; use StoreModelProduct; $customer = new Customer('Bob'); echo $customer->getName(); $product = new Product();

Code language: HTML, XML (xml)

When the number of imported classes grows, your code will become more verbose. So instead of importing each individual class, you can import all the classes using a single statement:

use namespace{className1, className2, ...}

Code language: PHP (php)

For example:

<?php require 'src/Model/Customer.php'; require 'src/Model/Product.php'; use StoreModel{Customer, Product}; $customer = new Customer('Bob'); echo $customer->getName(); $product = new Product();

Code language: HTML, XML (xml)

Alias classes from a namespace

First, create a new directory called Database under the project directory and place a new file Logger.php in the Database directory with the following code:

<?php namespace StoreDatabase; class Logger { public function log($message) { var_dump('Log ' . $message . ' to the database.'); } }

Code language: HTML, XML (xml)

Second, create a new directory Utils under the project directory and create a new Logger.php in the Utils directory.

<?php namespace StoreUtils; class Logger { public function log($message) { var_dump('Log ' . $message); } }

Code language: HTML, XML (xml)

Now, you have two classes with the same name in different namespaces:

. ├── index.php └── src ├── Database │ └── Logger.php ├── Model │ ├── Customer.php │ └── Product.php └── Utils └── Logger.php

Code language: plaintext (plaintext)

Third, import Logger classes from both namespaces StoreUtils and DatabaseLogger into the index.php file:

<?php require 'src/Utils/Logger.php'; require 'src/Database/Logger.php'; use StoreUtilsLogger; use StoreDatabaseLogger;

Code language: HTML, XML (xml)

PHP raises the following error:

Fatal error: Cannot use StoreDatabaseLogger as Logger because the name is already in use in...

Code language: plaintext (plaintext)

To avoid this, you can just import the namespaces:

<?php require 'src/Utils/Logger.php'; require 'src/Database/Logger.php'; use StoreUtils; use StoreDatabase; $loggers = [ new UtilsLogger(), new DatabaseLogger() ];

Code language: HTML, XML (xml)

Or you can give a class an alias when importing it:

import namespaceclassName as newClassName;

Code language: JavaScript (javascript)

The following example assigns the DatabaseLogger class an alias to the StoreDatabaseLogger class:

<?php require 'src/Utils/Logger.php'; require 'src/Database/Logger.php'; use StoreUtilsLogger; use StoreDatabaseLogger as DatabaseLogger; $loggers = [ new Logger(), new DatabaseLogger() ];

Code language: HTML, XML (xml)

Use classes from the global namespace

To use global classes such as built-in classes or user-defined classes without a namespace, you need to precede the name of such classes with a backslash ().

The following example shows how to use the built-in DateTime class in the App namespace:

<?php namespace App; $publish_at = new DateTime(); echo $publish_at->format('Y-m-d H:i:s');

Code language: HTML, XML (xml)

Summary

  • Use a namespace to group related classes.
  • Mimic the directory structure with the namespaces to make it easier to find the classes.
  • Use the use operator to import a namespace or a class from a namespace.
  • Use the as keyword to assign a namespace or a class of a namespace an alias.

Did you find this tutorial useful?

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error cannot set display mode перевод
  • Fatal error cannot set display mode serious sam 3 что делать
  • Fatal error cannot set display mode gfxapi error direct3d
  • Fatal error cannot redeclare phpmailerautoload
  • Fatal error cannot recover after last error any further errors will be ignored

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии