April 6, 2012

Interpolate constant (not variable) into heredoc?

Question by Michael

<?php
   define('my_const', 100);
   echo <<<MYECHO
      <p>The value of my_const is {my_const}.</p>
MYECHO;
?>

If i put a variable inside the braces it prints out. But not the constant. How can I do it?
Thank’s!

Answer by Starx

Use sprintf()

define('my_const', 100);
$string = <<< heredoc
      <p>The value of my_const is %s.</p>
heredoc;

$string = sprintf($string, my_const);
March 2, 2012

Does PHP have an equivalent of C/C++'s #ifdef?

Question by DavidH

I’m trying to define a constant, but I don’t want to redefine it if it’s already been defined.
Here’s a C sample:

#ifndef BASEPATH
#define BASEPATH /mnt/www
#endif

What is the most elegant way to do this in PHP?

Answer by rid

Use defined() and define().

if (!defined('BASEPATH')) {
    define('BASEPATH', '/mnt/www');
}

Answer by Starx

Use defined() function

if(!defined("constantname")) {
   define("constantname", "value");
}
...

Please fill the form - I will response as fast as I can!