Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static class variables -- in a heredoc

Tags:

html

php

I set up a class, which simplified is this:

class Labels {
    static public $NAMELABEL = "Name";
}

I successfully got the following code to work fine:

echo '<table border="1">';
  echo '<tr>';
  echo "<th>" . Labels::$NAMELABEL . "</th>";
  echo '</tr>';

 // the rest of the Table code not shown for brevity...

echo "</table>";

I see a table with a column header called Name when I run this -- so it works fine.

But not inside a heredoc -- I get "Notice: Undefined variable: NAMELABEL in C:\xampp........blah blah" when I run the following:

    echo <<<_END
       <form action="index.php" method="post"><pre>
       Labels::$NAMELABEL : <input type="text" name="author" />
       <input type="submit" value="ADD RECORD" />
    </pre></form>
_END;

I've tried all sorts of quoting, string concat operator '.', nothing works. I figured "Well I got the static class variables to work in an HTML table, why not a heredoc."

Dang I love heredocs, they come with a weird name and weird problems. It's the sort of mind-bending kind of fun I crave, heredocs are righteous little doosh monkeys.

I really want to use my static class variables here -- is there some combination of quoting/string concatenation that will allow me to embed them into my heredocs?

like image 865
wantTheBest Avatar asked Jun 09 '11 05:06

wantTheBest


1 Answers

Interpolation in heredocs works the same as in double quotes, so you can use curly brace ("complex") syntax.

However the parser does not recognize static class variables (see previous documentation). In order to refer to static class variables, you will need to set them locally as follows:

$label = Labels::$NAMELABEL;

echo <<<_END
    <form action="index.php" method="post"><pre>
       $label : <input type="text" name="author" />
       <input type="submit" value="ADD RECORD" />
    </pre></form>
_END;
like image 75
Jordan Running Avatar answered Oct 30 '22 05:10

Jordan Running