【问题标题】:How to use class with namespace in php?如何在 php 中使用带命名空间的类?
【发布时间】:2020-11-17 10:55:57
【问题描述】:

我尝试创建具有如下结构的应用程序:

App
 +--src
      Example.php
 +--vendor
    --
 composer.json
 composer.lock
 index.php

Example.php 设置namespace Example 然后在index.php 中使用它。 但它不起作用。

例子.php

<?php namespace Example

class Example {
    public function __construct()
    {
        echo 'constructed';
    }
}

index.php

<?php use Example\Example;

$example = new Example;

echo 'here ok';

但是当我在浏览器中运行它时,它的错误:

This page isn’t workinglocalhost is currently unable to handle this request.

我怎么了,有什么帮助吗?

【问题讨论】:

  • 请分享错误信息,以及您解决问题的尝试

标签: php namespaces composer-php


【解决方案1】:

既然你还没有发布你的composer.json包含的内容,至少你必须把它放在你的autoload中:

{
    "autoload": {
        "psr-4": {
            "Example\\": "src"
        }
    }
}

在您的index.php 中,您需要要求作曲家自动加载:

require_once 'vendor/autoload.php'; // add the autoloader

use Example\Example;

$example = new Example;

echo 'here ok';

最后,您需要运行 composer 来反映您的更改:

php composer dump-autoload

【讨论】:

    猜你喜欢
    • 2015-07-28
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    相关资源
    最近更新 更多