简体   繁体   中英

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 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';

error1 Class 'Gol' not found

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

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("myFile", "MyApp\\Conciliation\\Gol");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM