如果类在不同的命名空间中,则为未定义的类

时间:2016-01-18 18:11:56

标签: phpstorm

我在phpstorm 8.0.3上设置了yii2项目。我的命名空间结构如下:

backend\
  controllers
  models
  ...
frontend\
  controllers
  models
  ..
common\
  controllers
  models

我在项目中使用了composer,并在vendor文件夹中安装了各种依赖项。

每当我尝试使用不在同一基本命名空间(frontendbackendcommon)中的类时,我会得到一个未定义的类错误。奇怪的是,类的名称空间是自动完成的:

enter image description here

另一个奇怪的是,如果打开定义了类的文件,某些类的未定义类错误就会消失。

5 个答案:

答案 0 :(得分:9)

看起来PHPStorm缓存有点被破坏了。我最后通过转到File - >来使缓存失效。 Invalidate Caches/Restart。这删除了我的历史,但修复了未定义的类问题。

答案 1 :(得分:1)

您必须在use部分中声明nedded类或命名空间。例如,如果您需要使用BaseController命名空间中的custom\controllers

<?php
namespace frontend\components;

// Add this line
use common\controllers\BaseController;

class Controller extends BaseController {
}

答案 2 :(得分:1)

我不得不重置我的 PHPstorm 来解决“找不到类”的问题。

File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\Lib\site-packages\flask\app.py", line 2069, in __call__
    def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:
        """The WSGI server calls the Flask application object as the
        WSGI application. This calls :meth:`wsgi_app`, which can be
        wrapped to apply middleware.
        """
        return self.wsgi_app(environ, start_response)
 
    def _request_blueprints(self) -> t.Iterable[str]:
        if _request_ctx_stack.top.request.blueprint is None:
            return []
        else:
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\Lib\site-packages\flask\app.py", line 2054, in wsgi_app
            try:Open an interactive python shell in this frame
                ctx.push()
                response = self.full_dispatch_request()
            except Exception as e:
                error = e
                response = self.handle_exception(e)
            except:  # noqa: B001
                error = sys.exc_info()[1]
                raise
            return response(environ, start_response)
        finally:
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\Lib\site-packages\flask\app.py", line 2051, in wsgi_app
        ctx = self.request_context(environ)
        error: t.Optional[BaseException] = None
        try:
            try:
                ctx.push()
                response = self.full_dispatch_request()
            except Exception as e:
                error = e
                response = self.handle_exception(e)
            except:  # noqa: B001
                error = sys.exc_info()[1]
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\Lib\site-packages\flask\app.py", line 1501, in full_dispatch_request
            request_started.send(self)
            rv = self.preprocess_request()
            if rv is None:
                rv = self.dispatch_request()
        except Exception as e:
            rv = self.handle_user_exception(e)
        return self.finalize_request(rv)
 
    def finalize_request(
        self,
        rv: t.Union[ResponseReturnValue, HTTPException],
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\Lib\site-packages\flask\app.py", line 1499, in full_dispatch_request
        self.try_trigger_before_first_request_functions()
        try:
            request_started.send(self)
            rv = self.preprocess_request()
            if rv is None:
                rv = self.dispatch_request()
        except Exception as e:
            rv = self.handle_user_exception(e)
        return self.finalize_request(rv)
 
    def finalize_request(
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\Lib\site-packages\flask\app.py", line 1485, in dispatch_request
            getattr(rule, "provide_automatic_options", False)
            and req.method == "OPTIONS"
        ):
            return self.make_default_options_response()
        # otherwise dispatch to the handler for that endpoint
        return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
 
    def full_dispatch_request(self) -> Response:
        """Dispatches the request and on top of that performs request"""
        pre and postprocessing as well as HTTP exception catching and
        error handling.
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\app.py", line 226, in devices
 
# Renders the devices page.
@app.route('/devices')
def devices():
    if current_user.is_authenticated:
        device_list = androidmanagement.enterprises().devices().list(parent=enterprise_name, pageSize=200).execute()
 
        return render_template(
            'devices.html',
            title='Devices',
            year=datetime.now().year,
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\Lib\site-packages\googleapiclient\_helpers.py", line 134, in positional_wrapper
                )
                if positional_parameters_enforcement == POSITIONAL_EXCEPTION:
                    raise TypeError(message)
                elif positional_parameters_enforcement == POSITIONAL_WARNING:
                    logger.warning(message)
            return wrapped(*args, **kwargs)
 
        return positional_wrapper
 
    if isinstance(max_positional_args, six.integer_types):
        return positional_decorator
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\Lib\site-packages\googleapiclient\http.py", line 920, in execute
            )
            self.body = parsed.query
            self.headers["content-length"] = str(len(self.body))
 
        # Handle retries for server-side errors.
        resp, content = _retry_request(
            http,
            num_retries,
            "request",
            self._sleep,
            self._rand,
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\Lib\site-packages\googleapiclient\http.py", line 191, in _retry_request
            )
            sleep(sleep_time)
 
        try:
            exception = None
            resp, content = http.request(uri, method, *args, **kwargs)
        # Retry on SSL errors and socket timeout errors.
        except _ssl_SSLError as ssl_error:
            exception = ssl_error
        except socket.timeout as socket_timeout:
            # Needs to be before socket.error as it's a subclass of OSError
AttributeError: 'str' object has no attribute 'request'

请小心,它可以让一切正常,但它还可以让您备份当前的设置。在那之后,一切都被硬重置,现在又可以正常工作了。

答案 3 :(得分:0)

我认为你在使用composer autoload时遇到了一些问题。 试试:

composer update

答案 4 :(得分:0)

这是由于我的PHP语言设置而发生的。我是通过删除我的一个类中的名称空间发现的。错误更改为“标量类型仅在PHP 7中可用”。

转到SELECT DISTINCT code from TempTableExcelFile WHERE code in (SELECT Code from tblpeople) 。将File -> Settings -> Language & Frameworks -> PHP更改为语言版本7或更高版本。

编辑: 之后,PHP language level间歇性地以Insert -> Getters and Setters而不是mixed的形式生成函数和注释。我不知道为什么会这样,但是我手动重新创建了所有字段,从而解决了该问题。