如何在PHP中使用带有命名空间的类?
问题描述:
我尝试创建具有以下结构的应用程序:
I try to create app with structure as below:
App
+--src
Example.php
+--vendor
--
composer.json
composer.lock
index.php
在Example.php设置了 namespace Example
的位置,然后在 index.php
中使用它.但它不起作用.
Where Example.php set namespace Example
then use it inside index.php
.
but it not working.
Example.php
Example.php
<?php namespace Example
class Example {
public function __construct()
{
echo 'constructed';
}
}
index.php
index.php
<?php use Example\Example;
$example = new Example;
echo 'here ok';
但是当我在浏览器中运行它时,它的错误:
but when I runing it in browser, its error:
我怎么了,有什么帮助吗?
What am I wrong, any help?
答
由于您尚未发布 composer.json
所包含的内容,因此至少必须将其保存在 autoload中
:
Since you haven't posted what your composer.json
contains yet, at least you must have it in your autoload
:
{
"autoload": {
"psr-4": {
"Example\\": "src"
}
}
}
在您的 index.php
中,您需要从composer中自动加载:
In your index.php
, you need to require the autoload from composer:
require_once 'vendor/autoload.php'; // add the autoloader
use Example\Example;
$example = new Example;
echo 'here ok';
最后,您需要运行composer来反映您的更改:
Lastly, you need to run composer to reflect your changes:
php composer dump-autoload