Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

php - Using static class variables -- in a heredoc

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...