1

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!

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.