Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing defined variable inside <<<HTML in php

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 :)

like image 684
tftd Avatar asked Mar 09 '11 14:03

tftd


People also ask

How can get input field value in PHP variable?

In order to get an input value, you can use the htmlspecialchars() method and $_REQUEST variable. Note: The htmlspecialchars() method functions by converting special characters to HTML entities. The $_REQUEST variable is a built-in PHP variable that functions by getting data from the input field.


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

like image 139
Jeff Parker Avatar answered Sep 26 '22 01:09

Jeff Parker


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.

like image 32
Surreal Dreams Avatar answered Sep 24 '22 01:09

Surreal Dreams