PHP อนุญาตให้ฝัง HTML โดยตรงภายใน Control Structure (if, else, foreach, while) ได้หลายรูปแบบ เลือกใช้ตามความเหมาะสมและ Coding Style ของทีม
รูปแบบที่ 1: Alternative Syntax (แนะนำสำหรับ Template/View)
<a href="/dashboard">Dashboard</a>
<a href="/logout">Logout</a>
<a href="/login">Login</a>
<a href="/register">Register</a>
ข้อดี: อ่านง่าย, เห็น HTML Structure ชัดเจน, ไม่ต้อง Escape Quote
รูปแบบที่ 2: Alternative Syntax + Elseif
role === 'admin'): ?>
<div class="admin-panel">Admin Panel</div>
role === 'editor'): ?>
<div class="editor-tools">Editor Tools</div>
<div class="user-area">User Area</div>
รูปแบบที่ 3: Standard Braces + Echo (เหมาะสำหรับ Logic ภายใน Function)
<div class="user-card">
<h3>= htmlspecialchars($user->name) ?></h3>
isVerified): ?>
<span class="badge verified">Verified</span>
</div>
รูปแบบที่ 4: Inline Ternary / Null Coalescing (สำหรับค่าเล็กๆ)
<span class="status = $user->isActive ? 'active' : 'inactive' ?>">
= $user->isActive ? 'Active' : 'Inactive' ?>
</span>
<!-- Null Coalescing (PHP 7+) -->
<p>Welcome, = $user->nickname ?? $user->name ?? 'Guest' ?></p>
รูปแบบที่ 5: Heredoc / Nowdoc (สำหรับ HTML Block ใหญ่)
{$title}
{$content}
Read More
HTML;
echo $html;
?>
Best Practices
| สถานการณ์ | แนะนำ |
|---|---|
| Template/View File | Alternative Syntax (if(): ... endif;) |
| Logic ภายใน Function/Class | Standard Braces + Return String หรือ Heredoc |
| Condition แบบสั้น (1-2 บรรทัด) | Ternary / Null Coalescing |
| Loop (foreach/while) | Alternative Syntax |
ตัวอย่าง Loop + Condition
<article class="post">
<h2><a href="/post/= $post->slug ?>">= htmlspecialchars($post->title) ?></a></h2>
excerpt): ?>
<p class="excerpt">= htmlspecialchars($post->excerpt) ?></p>
<time>= $post->created_at->format('d/m/Y') ?></time>
</article>
⚠️ ข้อผิดพลาดที่พบบ่อย
- ลืม
endif;/endwhile;/endforeach; - ผสมผสาน Braces กับ Alternative Syntax ใน Block เดียว
- ไม่ Escape Output ด้วย
htmlspecialchars()(XSS Risk) - Logic ซับซ้อนเกินไปใน Template -> ควรย้ายไป View Model/Helper