Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 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 Reply

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...