[英]How to use class with namespace in php?
I try to create app with structure as below:我尝试创建具有如下结构的应用程序:
App
+--src
Example.php
+--vendor
--
composer.json
composer.lock
index.php
Where Example.php set namespace Example
then use it inside index.php
.其中 Example.php 设置
namespace Example
然后在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:但是当我在浏览器中运行它时,它的错误:
This page isn't workinglocalhost is currently unable to handle this request.此页面不工作 localhost 当前无法处理此请求。
What am I wrong, any help?我错了什么,有帮助吗?
Since you haven't posted what your composer.json
contains yet, at least you must have it in your autoload
:由于您还没有发布您的
composer.json
包含的内容,至少您必须在您的autoload
中包含它:
{
"autoload": {
"psr-4": {
"Example\\": "src"
}
}
}
In your index.php
, you need to require the autoload from composer:在您的
index.php
中,您需要从作曲家自动加载:
require_once 'vendor/autoload.php'; // add the autoloader
use Example\Example;
$example = new Example;
echo 'here ok';
Lastly, you need to run composer to reflect your changes:最后,您需要运行 composer 来反映您的更改:
php composer dump-autoload
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.