[英]How do you escape namespace string
New to namespace in php and trying to call a dummy class. PHP命名空间的新增功能,并尝试调用虚拟类。 Here is the code below
这是下面的代码
include "App/Controllers/Home.php";
// This code works but I commented it out to try it the otherway
//$home = new \App\Controllers\Home();
$namespace = "\App\Controllers\\";
$home = new $namespace . Home();
$home->index();
It shows error 显示错误
Fatal error: Uncaught Error: Class '\\App\\Controllers\\' not found in C:\\xampp\\htdocs\\namespace\\index.php:16 Stack trace: #0 {main} thrown in C:\\xampp\\htdocs\\namespace\\index.php on line 16
致命错误:未捕获错误:在C:\\ xampp \\ htdocs \\ namespace \\ index.php:16中找不到类'\\ App \\ Controllers \\':堆栈跟踪:#0 {main}抛出在C:\\ xampp \\ htdocs \\ namespace \\中第16行的index.php
I believe I am not escaping the namespace right, can you help? 我相信我没有逃避命名空间的权利,您能帮上忙吗?
As misorude suggest you can try : 如misorude建议,您可以尝试:
$namespace = "\\App\Controllers\\";
$classname = $namespace . 'Home';
$home = new $classname();
$home->index();
You should prefer using single-quote for namespaces - using double quote may result some surprising effects since some sequences have special meaning if they're enclosed in double-quotes. 您应该首选对名称空间使用单引号-使用双引号可能会产生一些令人惊讶的效果,因为如果某些序列用双引号引起来,则它们具有特殊的含义 。 With single-quotes you need to care only about trailing
\\
since \\'
will work as escaped '
and it will not be interpreted as end of the string: 使用单引号时,您只需要关心尾随
\\
因为\\'
将作为转义的'
起作用,并且不会被解释为字符串的结尾:
$namespace = 'App\Controllers\\';
But this is unusual situation, usually you're using FQN, so there is no such problem: 但这是不寻常的情况,通常您使用的是FQN,因此没有这样的问题:
$className = 'App\Controllers\Home';
$home = new $className();
Or just use ::class
- this is more IDE and SCA firendly: 或仅使用
::class
class-这更像是IDE和SCA:
$className = \App\Controllers\Home::class;
$home = new $className();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.