The following does not work:

use application\components\auditor\AuditLevel;


public function actionAudit()
{
    $data=unserialize($_POST['data']);
    $message=$data['message'];
    $context=$data['context'];
    $level=$context['level'];
    Yii::app()->auditor->log(constant('AuditLevel::'.$level), $message, $context);
}

// constant(): Couldn't find constant AuditLevel::INFO

But having all namespace works:

use application\components\auditor\AuditLevel;


public function actionAudit()
{
    $data=unserialize($_POST['data']);
    $message=$data['message'];
    $context=$data['context'];
    $level=$context['level'];
    Yii::app()->auditor->log(constant('application\components\auditor\AuditLevel::'.$level), $message, $context);
}

Any idea how can I use the namespace declared above instead of in the function?

Thanks!

有帮助吗?

解决方案

From the php.net comment section on constant():

As of PHP 5.4.6 constant() pays no attention to any namespace aliases that might be defined in the file in which it's used. I.e. constant() always behaves as if it is called from the global namespace.

You have to use the full namespace path.

其他提示

All class names passed as string are "immune" to the current namespace and aliases, they are all fully qualified names, always. Whether you're instantiating a new class by variable or resolve a constant by string name, you always need to use the FQN. It's only practical: strings can be passed from one namespace to another, it's impossible to create clear resolution rules for them.

You can use the __NAMESPACE__ keyword.

Yii::app()->auditor->log(constant(__NAMESPACE__ . '\AuditLevel::'.$level), $message, $context);

Of course this will work just in the same namespace - otherwise you need to provide full path [which sounds reasonable to me].

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top