Essential PHP Concepts Every Developer Should Know

PHP

Variables

PHP variables start with a $ sign and are dynamically typed.

<?php
$name = "Alice";
$age = 30;
$price = 19.99;
?>

Arrays

Arrays can be indexed or associative.

<?php
// Indexed array
$colors = ["red", "green", "blue"];
// Associative array
$user = ["name" => "Alice", "age" => 30];
?>

Functions

Functions encapsulate reusable logic.

<?php
function greet($name) {
    return "Hello, $name!";
}
echo greet("Alice");
?>

Object-Oriented Programming

PHP supports classes, objects, inheritance, and interfaces.

<?php
class User {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
    public function greet() {
        return "Hello, $this->name!";
    }
}
$user = new User("Alice");
echo $user->greet();
?>

Superglobals

Special global arrays like $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER provide access to request and environment data.

<?php
$name = $_GET['name'] ?? 'Guest';
echo "Hello, $name!";
?>

Sessions & Cookies

Sessions and cookies are used to persist user data across requests.

<?php
// Start session
session_start();
$_SESSION['user'] = 'Alice';
// Set cookie
setcookie('theme', 'dark', time()+3600);
?>

File Handling

PHP can read, write, and manipulate files easily.

<?php
// Write to a file
file_put_contents('example.txt', "Hello World");
// Read from a file
$content = file_get_contents('example.txt');
echo $content;
?>

Error & Exception Handling

Use try, catch, and finally for robust error handling.

<?php
try {
    throw new Exception("Something went wrong!");
} catch (Exception $e) {
    echo $e->getMessage();
} finally {
    // Always runs
}
?>

Form Handling & Validation

Process and validate user input from forms.

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    if ($email) {
        echo "Valid email: $email";
    } else {
        echo "Invalid email.";
    }
}
?>

Regular Expressions

Use preg_match and preg_replace for pattern matching.

<?php
$text = "My phone: 123-456-7890";
if (preg_match('/\d{3}-\d{3}-\d{4}/', $text, $matches)) {
    echo "Found: " . $matches[0];
}
?>

Date & Time Functions

Work with dates and times using built-in functions.

<?php
echo date('Y-m-d H:i:s');
$now = new DateTime();
echo $now->format('l, F j, Y');
?>

HTTP Requests (cURL)

Use cURL to make HTTP requests to other servers.

<?php
$ch = curl_init('https://api.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>

JSON Encoding/Decoding

Convert data to and from JSON format.

<?php
$data = ['name' => 'Alice', 'age' => 30];
$json = json_encode($data);
$decoded = json_decode($json, true);
?>

Autoloading & PSR Standards

Use autoloading for classes and follow PSR standards for interoperability.

<?php
spl_autoload_register(function ($class) {
    include $class . '.php';
});
?>

Environment Variables & Configuration

Store sensitive data in environment variables and config files.

<?php
$db_host = getenv('DB_HOST');
?>

PHP 8 Features

  • Attributes (annotations)
  • Union types
  • Match expression
  • Constructor property promotion
  • Named arguments
<?php
// Match expression
$result = match($status) {
    'success' => '✅',
    'error' => '❌',
    default => '⏳',
};
?>

Security Best Practices

  • Validate and sanitize user input
  • Use prepared statements for SQL queries
  • Escape output to prevent XSS
  • Use password hashing (password_hash)
  • Keep PHP and dependencies updated

Design Patterns in PHP

Common patterns like Singleton, Factory, and Observer help organize code.

<?php
class Singleton {
    private static $instance;
    private function __construct() {}
    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}
?>

Dependency Injection

Pass dependencies to objects for flexibility and testability.

<?php
class Logger {}
class UserService {
    private $logger;
    public function __construct(Logger $logger) {
        $this->logger = $logger;
    }
}
?>

RESTful APIs with PHP

Build APIs using PHP and handle JSON requests/responses.

<?php
header('Content-Type: application/json');
$data = ['status' => 'success'];
echo json_encode($data);
?>

Testing (PHPUnit)

Write unit tests for PHP code using PHPUnit.

// Example PHPUnit test
class UserTest extends \PHPUnit\Framework\TestCase {
    public function testGreet() {
        $user = new User('Alice');
        $this->assertEquals('Hello, Alice!', $user->greet());
    }
}

Working with Databases

Use PDO or MySQLi for secure database access.

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->prepare('SELECT * FROM users');
$stmt->execute();
$users = $stmt->fetchAll();
?>

Frameworks (Laravel, Symfony)

Popular frameworks provide structure and features for rapid development.

  • Laravel: Eloquent ORM, routing, Blade templates
  • Symfony: Components, bundles, robust architecture

Internationalization (i18n)

Support multiple languages using gettext or custom solutions.

<?php
putenv('LC_ALL=en_US');
setlocale(LC_ALL, 'en_US');
bindtextdomain('messages', './locale');
textdomain('messages');
echo gettext('Hello');
?>

Performance Optimization

  • Use opcode caching (OPcache)
  • Profile code with Xdebug
  • Optimize database queries
  • Minimize I/O operations

Working with XML

Parse and generate XML using SimpleXML or DOMDocument.

<?php
$xml = simplexml_load_string('Alice');
echo $xml->name;
?>

CLI Scripts in PHP

Write command-line scripts for automation and maintenance.

<?php
if (php_sapi_name() === 'cli') {
    echo "Running from CLI";
}
?>

Advanced Concepts

  • Namespaces
  • Traits
  • Type declarations
  • Error handling (try/catch)
  • Composer for dependency management