我在目录Main
中有文件Helpers
;
Main
内的目录Helper
内容为Helpers\Helper
。
我尝试将index.php
中的课程<?
namespace Program;
use Helpers\Helper;
class Index {
public function __construct()
{
$class = new Helper();
}
}
注入:
d = {'a':5 , 'b':4, 'c':3, 'd':3, 'e':1}
x = sorted(((v,k) for k,v in d.items()))
print(x[-2][1])
print(x[-3][1])
但它不起作用。
如何使用命名空间并在PHP中使用?
答案 0 :(得分:2)
根据您的描述,您的目录结构应该与此类似:
Main*
-- Index.php
|
Helpers*
--Helper.php
如果您关于PSR-4标准,那么您的班级定义可能类似于以下所示:
<强>的index.php 强>
<?php
// FILE-NAME: Index.php.
// LOCATED INSIDE THE "Main" DIRECTORY
// WHICH IS PRESUMED TO BE AT THE ROOT OF YOUR APP. DIRECTORY
namespace Main; //<== NOTICE Main HERE AS THE NAMESPACE...
use Main\Helpers\Helper; //<== IMPORT THE Helper CLASS FOR USE HERE
// IF YOU ARE NOT USING ANY AUTO-LOADING MECHANISM, YOU MAY HAVE TO
// MANUALLY IMPORT THE "Helper" CLASS USING EITHER include OR require
require_once __DIR__ . "/helpers/Helper.php";
class Index {
public function __construct(){
$class = new Helper();
}
}
<强> Helper.php 强>
<?php
// FILE NAME Helper.php.
// LOCATED INSIDE THE "Main/Helpers" DIRECTORY
namespace Main\Helpers; //<== NOTICE Main\Helpers HERE AS THE NAMESPACE...
class Helper {
public function __construct(){
// SOME INITIALISATION CODE
}
}