dev.rean.me
php

VS Code PHP Shorthand & Snippets — Complete Guide with Tips

Master PHP code snippets, tag shorthands, OOP class/function shortcuts, Emmet configuration for PHP templates, custom user snippets, and VS Code productivity tips.

2026-09-11 · 8 min read

Share:

VS Code PHP Shorthand & Snippets — Code PHP 10× Faster!

Hello friend! Writing PHP scripts, HTML template tags (<?php echo $var; ?>), loops, and object-oriented class structures by hand takes a lot of repetitive typing.

Did you know that with VS Code snippets, extensions, and configuration, you can generate PHP functions, class constructors, foreach loops, and var_dump() debug statements in milliseconds?

In this complete guide, we cover all essential PHP shorthands, HTML template tags, OOP shortcuts, Emmet configuration in .php files, custom snippets, and pro tips to boost your PHP development speed!

💡 Tip: Combine VS Code's built-in snippets with the PHP Intelephense extension for the ultimate PHP coding environment!

If you want to explore more PHP, HTML, CSS, JS, and ReactJS guides:


1. PHP Open Tags & Debug Shorthands

Open Tags & Echo Shortcuts

Shorthand / TagExpands To / SyntaxDescription
php + Tab<?php ?>Standard PHP tag block
<?= $var ?><?php echo $var; ?>Short echo tag (Native PHP shortcut)
pe<?php echo $1; ?>PHP echo statement
vdvar_dump($var); die();Debug variable and halt execution
prprint_r($var);Print readable array output
prdprint_r($var); die();Print array output and halt

💡 PHP Short Echo Tag: In modern PHP (7.0+ & 8.x), <?= $name ?> is always enabled and is the clean standard for outputting variables inside HTML files!


2. Control Structure & Loop Shorthands

Writing loops and conditional branches in PHP is super fast using these built-in snippet prefixes:

ShorthandExpands ToUsage
ifif (condition) { }Standard if block
ifelif (condition) { } else { }if...else block
foreforeach ($array as $value) { }Iterate array values
forekforeach ($array as $key => $value) { }Iterate array key-value pairs
forfor ($i = 0; $i < $count; $i++) { }Standard for loop
whwhile (condition) { }while loop
swswitch ($var) { case 'val': break; default: break; }switch statement
try / tryctry { } catch (Exception $e) { }Try-catch error handling

Alternative Syntax for HTML Templates

When embedding PHP inside HTML views, the alternative colon syntax is much cleaner:

<!-- Clean alternative foreach for HTML views: -->
<?php foreach ($users as $user): ?>
    <div class="user-card">
        <h3><?= $user['name'] ?></h3>
        <p>Email: <?= $user['email'] ?></p>
    </div>
<?php endforeach; ?>

3. Object-Oriented PHP (OOP) Shorthands

Creating classes, methods, and properties in PHP is effortless with method visibility shortcuts:

ShorthandExpands ToDescription
classclass ClassName { }Create PHP class
pubfpublic function name() { }Public method
profprotected function name() { }Protected method
prifprivate function name() { }Private method
pubsfpublic static function name() { }Public static method
con / __constructpublic function __construct() { }Class constructor

Modern PHP 8 Constructor Promotion Shorthand

In PHP 8.0+, you can declare and initialize class properties directly inside the constructor:

class User {
    // PHP 8 Constructor Property Promotion:
    public function __construct(
        public int $id,
        public string $name,
        public string $email
    ) {}
}

4. Enable Emmet HTML Shorthands inside .php Files

By default, typing Emmet abbreviations like div.container>ul>li*3 doesn't expand inside .php files.

How to Fix This in VS Code Settings:

Open your .vscode/settings.json file and add "php": "html" under emmet.includeLanguages:

{
  "emmet.includeLanguages": {
    "php": "html"
  }
}

Now, typing ! + Tab inside any .php file generates a complete HTML5 template, and all HTML Emmet shortcuts work seamlessly!


5. Essential VS Code Extensions for PHP Development

Install these 4 essential extensions to turn VS Code into a powerful PHP IDE:

1. PHP Intelephense (by Ben Mewburn)

  • Marketplace ID: bmewburn.vscode-intelephense-client
  • Why you need it: Super fast autocompletion, detailed code signatures, type checking, auto-import namespaces (use App\Models\User;), and go-to-definition support.

2. PHP Awesome Snippets

  • Marketplace ID: Hridoy.php-awesome-snippets
  • Why you need it: Unlocks over 100+ shorthand snippets for PHP 8, OOP, arrays, PDO database queries, and superglobals ($_POST, $_GET, $_SESSION).

3. PHP Debug (Xdebug)

  • Marketplace ID: xdebug.php-debug
  • Why you need it: Connects VS Code to Xdebug for step-by-step debugging, breakpoints, and inspecting variable values live while running scripts.

4. PHP CS Fixer / PHP CodeSniffer

  • Marketplace ID: junstyle.php-cs-fixer
  • Why you need it: Formats your PHP code automatically according to official PSR-12 coding standards on save.

6. How to Create Custom PHP Snippets in VS Code

You can create custom snippets for PDO database connections, JSON responses, or XSS security sanitization!

Step 1: Open php.json Snippets File

Press Ctrl + Shift + P → search "Snippets: Configure User Snippets" → select php (or php.json).

Step 2: Add Custom Snippet Configuration

{
  "Dump and Die Debug": {
    "prefix": "dd",
    "body": [
      "echo '<pre>';",
      "var_dump($1);",
      "echo '</pre>';",
      "die();"
    ],
    "description": "Pretty print var_dump and die"
  },
  "Sanitize Output (XSS)": {
    "prefix": "esc",
    "body": [
      "htmlspecialchars($1, ENT_QUOTES, 'UTF-8')"
    ],
    "description": "XSS Sanitization helper"
  },
  "JSON API Response": {
    "prefix": "jsonres",
    "body": [
      "header('Content-Type: application/json');",
      "echo json_encode([",
      "    'status' => '$1',",
      "    'message' => '$2',",
      "    'data' => $3",
      "]);",
      "exit();"
    ],
    "description": "Send JSON API Response"
  },
  "PDO Database Connection": {
    "prefix": "pdoconn",
    "body": [
      "try {",
      "    $$pdo = new PDO('mysql:host=localhost;dbname=$1;charset=utf8mb4', '$2', '$3', [",
      "        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,",
      "        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC",
      "    ]);",
      "} catch (PDOException $$e) {",
      "    die('Database connection failed: ' . $$e->getMessage());",
      "}"
    ],
    "description": "PDO Connection Template"
  }
}

Now typing dd, esc, jsonres, or pdoconn inside any PHP file instantly outputs your full template!


7. Pro VS Code Tips for PHP Developers

Tip 1: Disable Built-In PHP Validation

If you install PHP Intelephense, disable built-in VS Code PHP validation to prevent duplicate error warnings.

Add to settings.json:

{
  "php.validate.enable": false,
  "php.suggest.basic": false
}

Tip 2: Automatic Namespace Auto-Import

Intelephense can automatically insert use App\Services\AuthService; at the top of your file when you type AuthService.

Press Ctrl + . on any un-imported class name to pick the correct namespace import instantly!

Tip 3: Generate PHPDoc Comments Automatically

Type /** above any class, property, or function and press Enter. VS Code generates formatted PHPDoc comments with @param, @return, and @throws tags.

/**
 * Get user profile by ID
 * 
 * @param int $userId
 * @return array|null
 */
public function getUserProfile(int $userId): ?array {
    // ...
}

Summary — Top PHP Shorthands Cheat Sheet

ShorthandExpands ToCategory
php<?php ?>Tags
<?= $v ?><?php echo $v; ?>Output
vd / ddvar_dump(); die();Debugging
forekforeach ($arr as $k => $v)Loop
pubfpublic function name()OOP Method
prifprivate function name()OOP Method
conpublic function __construct()OOP Constructor
tryctry { } catch(Exception $e) { }Error handling
! + TabComplete HTML5 template in .phpEmmet

📚 Read More PHP & Web Development Tutorials

Expand your backend and web development skills with our tutorials:

Happy coding PHP! 🎉 Speed up your backend development with these powerful shorthands and extensions!

← Back to php
Share: