gpt4 book ai didi

PHP实例化obj类,变量不起作用

转载 作者:行者123 更新时间:2023-12-04 16:56:05 25 4
gpt4 key购买 nike

我发现了一个问题,我不确定是 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 'Gol' not found



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

最佳答案

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

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

因此,您调用 equalizeFile应该是这样的:

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

关于PHP实例化obj类,变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29720593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com