通过在名称之间使用变量使类动态化

时间:2017-12-28 05:00:20

标签: php dynamic-programming

我在bundle中的大多数类都具有相同的名称。 CRMFirstSecondExternal或CRMSecondThirdExternal等。现在我需要将FirstSecond或SecondThird存储到$变量中,然后在类名之间使用该$变量,以使其成为对该类的正确调用。

use Escalon\Bundle\Admin\CRMBundle\Helper\CRMTravelExpenseExternal;
private function deletePreviousSchedule( $params )
{
    $queryParams = array();
    $em = $this->getDoctrine()->getManager();

    if($params['bundleAndTableName'] == 'EscalonAdminCRMBundle:ClientServiceTe')
    {
        $helper = 'TravelExpense';
    }
    //$helper = preg_replace("/[^a-zA-Z]/", "", $helper);
    $crmEntityObject = new CRM.$helper.External;
    $crmEntityObject -> deletePreviousScheduleExternal($params);
}

错误:致命错误:未捕获错误:找不到类'Escalon \ Bundle \ Admin \ CRMBundle \ Controller \ CRM'。

1 个答案:

答案 0 :(得分:1)

问题是类名没有正确连接。试试这个功能

private function deletePreviousSchedule($params)
{
    $queryParams = array();
    $em = $this->getDoctrine()->getManager();

    if($params['bundleAndTableName'] == 'EscalonAdminCRMBundle:ClientServiceTe')
    {
        $helper = 'Escalon\Bundle\Admin\CRMBundle\Helper\CRMTravelExpenseExternal';
    }

    $crmEntityObject = new $helper();
    $crmEntityObject->deletePreviousScheduleExternal($params);
}

您可以在此处找到更多相关文档 - http://php.net/manual/en/language.namespaces.dynamic.php

此外,还可以

use Escalon\Bundle\Admin\CRMBundle\Helper\CRMTravelExpenseExternal;
private function deletePreviousSchedule($params)
{
    $queryParams = array();
    $em = $this->getDoctrine()->getManager();

    if($params['bundleAndTableName'] == 'EscalonAdminCRMBundle:ClientServiceTe')
    {
        $helper = 'TravelExpense';
    }

    $className = "Escalon\Bundle\Admin\CRMBundle\Helper\CRM{$helper}External";
    $crmEntityObject = new $className();
    $crmEntityObject->deletePreviousScheduleExternal($params);
}