dongyu1979 2013-01-23 22:15
浏览 26
已采纳

如何在PHP中解析常量

Is it possible to parse the contents of a constant in PHP?

For example,

define('WHO_AM_I', 'My name is $_SESSION['who_am_i'].'); // setup the constant string
echo eval(WHO_AM_I); // something like this -- but the eval() returns an error

Please note that I do not know the value of the _SESSION var until I actually use the constant later in the script stream.

Thanks.

AMENDED WITH REASON FOR WANTING TO DO THIS

I want to pull "hard coding" out of my script and give the user the ability to configure certain taxonomy in their site. So while I was doing this I also wanted to create a quasi-dynamic constant that I thought I might be able to parse later in the script.

If it can't be done...then it can't be done.

Don't shoot me for asking the question though.

A FINAL COMMENT TO AVOID ALL THIS CONFUSION

The purpose of my question has nothing to do with the eval() function. I am actually regretting having put it in there in the first place.

I put the eval() in the question simply to demonstrate to stackoverflow members that I did a bit if prep on my question rather than asking an open ended -- hey give me a solution without having offered any stab at it myself. So please disregard the eval().

All I want to know is can I somehow craft a define() in an way that makes the assigned value parse-able later in my script. That's it, that's all.

AMENDMENT C

I know I can do the following although I don't want to do it this way:

define('PARSE_ABLE_CONSTANT_PART_A', 'My name is ');
define('PARSE_ABLE_CONSTANT_PART_B', '.');

...later down the script road...

echo PARSE_ABLE_CONSTANT_PART_A . $_SESSION['who_am_i'] . PARSE_ABLE_CONSTANT_PART_B;

I just don't want to do it this way if I can make it slicker using an embedded var in the constant.

  • 写回答

2条回答 默认 最新

  • doucou19961205 2013-01-23 22:19
    关注

    Constants by definition don't allow you to set it with dynamic content.

    Here is a quote from the php manual:

    As the name suggests, that value cannot change during the execution of the script

    You can see more by going here

    You might be thinking of magical constants

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染