PHP实例化变量无效的obj类

时间:2015-04-18 17:35:16

标签: php namespaces composer-php

我发现了一个问题,我不确定是不是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);

    }

注意,$providerName = 'Gol';

  

ERROR1    Class&#39; Gol&#39;找不到

http://inft.ly/N8Q6F4B

那么,有什么方法可以保持使用变量来实例化类似上面的别名?


编辑,问题解决:工作示例

<?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);
    }

1 个答案:

答案 0 :(得分:1)

http://php.net/manual/en/language.namespaces.dynamic.php

如果要动态调用该类,则必须使用该类的完整路径。

因此,您对equalizeFile的调用应该类似于:

equalizeFile("myFile", "MyApp\\Conciliation\\Gol");