[英]PHP Instantiate obj class with variable not working
I found a problem that I not sure if is a bug of the php or on my code (probably mine) so let me show you what is happening: 我发现了一个我不确定是PHP还是我的代码错误的问题(可能是我的),所以让我向您展示发生了什么:
<?php namespace MyApp\Conciliation;
use SimpleExcel\SimpleExcel;
use ForceUTF8\Encoding;
use MyApp\Conciliation\Gol;
class Conciliation {
protected function equalizeFile($file, $providerName)
{
$type = false;
$nfile = 'public'.$file;
// TEST 1: the ideal aproach. not working (see error#1 bellow)
$provider = new $providerName();
// TEST 2: working, getting the correct response
$provider = new Gol();
// TEST 3: working, getting the correct response
$provider = new MyApp\Conciliation\Gol();
$provider->equalize($nfile);
}
Note, the $providerName = 'Gol';
注意,
$providerName = 'Gol';
error1 Class 'Gol' not found
error1 找不到类别'Gol'
http://inft.ly/N8Q6F4B http://inft.ly/N8Q6F4B
So, there is any way that I could keeping using variables to instantiate aliases similar as above? 因此,有什么办法可以让我继续使用变量来实例化别名,就像上面一样?
Edit, Problem solved: working example 编辑,已解决问题:工作示例
<?php namespace MyApp\Conciliation;
use SimpleExcel\SimpleExcel;
use ForceUTF8\Encoding;
class Conciliation {
protected function equalizeFile($file, $providerName)
{
$type = false;
$nfile = 'public'.$file;
$providerName = "MyApp\\Conciliation\\".$providerName;
$provider = new $providerName();
$provider->equalize($nfile);
}
http://php.net/manual/en/language.namespaces.dynamic.php http://php.net/manual/en/language.namespaces.dynamic.php
If you are calling the class dynamically, you have to use the full path to the class. 如果要动态调用该类,则必须使用该类的完整路径。
So, your call to equalizeFile
should be something like: 因此,您对
equalizeFile
的调用应类似于:
equalizeFile("myFile", "MyApp\\Conciliation\\Gol");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.