Home » Php » constants – Accessing defined variable inside <<<HTML in php

constants – Accessing defined variable inside <<<HTML in php

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m trying to figure out how to use a defined variable when using <<<HTML in php.
This is an example of what I want to achieve:

<?php
define('TEST','This is a test');
echo <<<HTML
Defined: {TEST}
HTML;
?>

What’s the appropriate way of getting the defined “TEST” inside the <<<HTML ?

Edit:
I did a small test to check which one of the methods is the fastest.
For my test I used 20 variables inside heredoc. Here is what happened with the different methods (in seconds):
Accessing defined variable inside <<<HTML in php seems to be the slowest way of doing it – 0.00216103.
Accessing defined variable inside <<<HTML in php is faster – 0.00073290.
Accessing defined variable inside <<<HTML in php is even faster – 0.00052595.
Accessing defined variable inside <<<HTML in php is the fastest – 0.00011110.

Hope this helps somebody else 🙂

How to&Answers:

It’s not pretty I’m afraid, but …

define('TEST','This is a test');

var $defined = TEST;

echo <<<HTML
Defined: {$defined}
HTML;

There isn’t, so far as I’m aware at least, a way of using defined values directly in that context, you need to use a variable.

Answer:

Here’s a method I found in the notes on the php manual: http://www.php.net/manual/en/function.define.php#100449

It’s a little convoluted, but it should work.

<?php
define('TEST','This is a test');

$cst = 'cst';
function cst($constant){
    return $constant;
}

echo <<<HTML
Defined: {$cst(TEST)}
HTML;

If you have multiple defined CONSTANTS to include, this would be better than manually assigning lots of variables to the value of constants.

Answer:

You can create a class that acts like an accessor to constants:

class DefineAccessor {
    function __get($name) {
        if (defined($name))
            return eval('return ' . $name . ';');
    }
}

Create an instance of it to be able to use it in heredoc:

$defines = new DefineAccessor;

And then use it like this:

echo <<<HTML
Defined: $defines->TEST
HTML;

Answer:

You can’t. Assign its value into a real variable.

Answer:

Only this way
http://ru2.php.net/manual/en/language.types.string.php#74744