PHP sözdizimi bu tür nedir?

4 Cevap php
$test= <<<EOF

....

EOF;

Ne için kullanılır, önce onu görmek hiç?

4 Cevap

Bu değişken interpolasyon ile, birden fazla satır, dizeleri tanımlamak için bir yoldur ki, HEREDOC syntax denir.


Quoting the manual page :

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

(There is more to read, that I didn't copy-paste from the manual page)


And, as very quick and simple example :

$a = 'World';
$string = <<<MARKER
<p>
  Hello, $a!
</p>
MARKER;
echo $string;

Bu çıktıyı verecektir:

Hello, World! 

Ve bu HTML kaynak:

<p>
  Hello, World!
</p>

İşte Heredoc olurdu

http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Blockquote A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

Kapanış tanımlayıcı satırın ilk sütununda başlamalıdır. Ayrıca, tanımlayıcı PHP başka bir etiket olarak aynı isimlendirme kurallarına uymalıdır: sadece alfanümerik karakterler ve alt çizgi içermelidir ve rakam olmayan bir karakter ile başlayabilir veya altını gerekir.

Nitekim, bu Heredoc sözdizimi.

Sadece durumda bunu düzenli dize sınırlayıcı vs var ne ilgi merak ediyor:

// These strings contain the same thing '"'"
$s1 = '\'"\'"';
$s2 = "'\"'\"";
$s3 = <<<EOS
'"'"
EOS

No more quote escaping.
A typical use case for me is when I need to store in a string some HTML code I have copy/pasted.