简体   繁体   中英

Why won't this work in PHP?

$constPrefix = '_CONST_';

if (strstr($content, $constPrefix)) {
    $constants = array('PHP_VERSION', '__FILE__');
    foreach($constants as $constant) {
        $constantOutput = eval($constant);
        $content = str_replace($constPrefix . $constant, $constantOutput, $content);
    }
}

Basically, just trying to parse some content and replace strings inside with the equivalent PHP constant. Is eval() what I should be using here? I've never actually found a reason to use it before, and it's almost 1am, and am wondering if that is a coincidence?

您可以使用常量替换eval

$constantOutput = constant($constant);

Why don't you just leave out the eval?

<?php
    $v = PHP_VERSION;
    $f = __FILE__;

    echo $v.' '.$f;
?>

gives

/tmp% php test.php 
5.2.10-2ubuntu6.4 /tmp/test.php

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