【问题标题】:define and heredoc定义和heredoc
【发布时间】:2012-01-04 18:55:10
【问题描述】:

如何在heredoc 中使用define?例如:

define('PREFIX', '/holiday');

$body = <<<EOD
<img src="PREFIX/images/hello.png" />   // This doesn't work.
EOD;

【问题讨论】:

    标签: php heredoc


    【解决方案1】:

    取自the documentation regarding strings

    DEFINE('PREFIX','/holiday');
    
    $const = PREFIX;
    
    echo <<<EOD
    <img src="{$const}/images/hello.png" /> 
    EOD;
    

    【讨论】:

    • 谢谢!添加一点注释:$const/images/hello.png 也可以。
    • 本例中不需要大括号。
    • 您也可以使用$consts = get_defined_constants(); 获取所有定义,然后使用{$consts['PREFIX']} 访问。
    【解决方案2】:

    如果你有超过 1 个常量,变量的使用会很困难。所以试试这个方法

    define('PREFIX', '/holiday');
    define('SUFFIX', '/work');
    define('BLABLA', '/lorem');
    define('ETC', '/ipsum');
    
    $cname = 'constant'; // if you want to use a function in heredoc, you must save function name in variable
    
    $body = <<<EOD
    <img src="{$cname('PREFIX')}/images/hello.png" />
    <img src="{$cname('SUFFIX')}/images/hello.png" />
    <img src="{$cname('BLABLA')}/images/hello.png" />
    <img src="{$cname('ETC')}/images/hello.png" />
    EOD;
    

    http://codepad.org/lA8L2wQR

    【讨论】:

    • 我按照您的建议尝试了该方法,因为我认为这很有趣,但我想到您的建议似乎未经测试,因为它给出了很多错误。
    • (嗯。疯了。我永远不会......)与@nbonniot 相比,任何关于速度的想法答案:stackoverflow.com/questions/10041200/…
    【解决方案3】:

    heredoc 语法中使用的常量不会被解释!

    编者注:这是真的。 PHP 无法识别 来自 heredoc 块中任何其他字符串的常量。

    Source

    【讨论】:

    猜你喜欢
    • 2018-01-07
    • 2017-11-21
    • 2011-05-15
    • 2018-10-02
    • 1970-01-01
    • 2016-08-24
    • 2013-06-15
    • 2011-07-16
    • 2013-11-10
    相关资源
    最近更新 更多