我发现了一个问题,我不确定是 php 的错误还是我的代码(可能是我的错误),所以让我向您展示发生了什么:
<?php namespace MyAppConciliation;
use SimpleExcelSimpleExcel;
use ForceUTF8Encoding;
use MyAppConciliationGol;
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 MyAppConciliationGol();
$provider->equalize($nfile);
}
请注意,$providerName = 'Gol';
错误1未找到类"Gol"
http://inft.ly/N8Q6F4B
那么,有什么方法可以继续使用变量来实例化类似于上述的别名?
编辑,问题解决:工作示例
<?php namespace MyAppConciliation;
use SimpleExcelSimpleExcel;
use ForceUTF8Encoding;
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
如果要动态调用类,则必须使用类的完整路径。
因此,您对equalizeFile
的调用应该是这样的:
equalizeFile("myFile", "MyApp\Conciliation\Gol");