Referensi lengkap PHP 8.3 & 8.4. Property hooks, typed constants, modern features, dan best practices. Perfect buat backend development.
Panduan awal untuk mulai menggunakan PHP sebagai bahasa pemrograman web server-side.
Cara menandai kode PHP agar bisa dijalankan oleh web server.
<?php
// Standard PHP tag
echo "Hello World";
// Short echo tag (always available)
<?= "Hello World" ?>
// Inline PHP
<?php echo "Hello"; ?>Berbagai cara untuk menambahkan komentar dalam kode PHP.
<?php
// Single line comment
# Single line comment (style Unix)
/*
* Multi-line comment
* Bisa banyak baris
*/
/**
* DocBlock comment
* Buat dokumentasi function/class
*/Fungsi-fungsi untuk menampilkan output ke browser atau console.
<?php
// Echo - bisa multiple parameters
echo "Hello", " ", "World";
echo "Hello World";
// Print - cuma satu parameter, return value
print "Hello World";
// Print_r - buat debug array/object
print_r($array);
// Var_dump - detailed info dengan type
var_dump($variable);
// Var_export - output valid PHP code
var_export($array);Dasar-dasar variabel dan berbagai tipe data yang tersedia di PHP.
Cara mendeklarasikan dan menggunakan variabel dalam PHP.
<?php
// Variable diawali $
$name = "Budi";
$age = 25;
$price = 99.99;
// Variable variables
$var = "hello";
$$var = "world";
echo $hello; // Output: world
// Constants
define('PI', 3.14159);
const API_KEY = 'abc123';
echo PI; // 3.14159
echo API_KEY; // abc123Berbagai tipe data yang didukung oleh PHP.
<?php
// String
$name = "Budi";
$greeting = 'Hello';
// Integer
$age = 25;
$hex = 0x1A; // Hexadecimal
$binary = 0b1010; // Binary
// Float
$price = 99.99;
$scientific = 1.2e3; // 1200
// Boolean
$isActive = true;
$isDone = false;
// Array
$numbers = [1, 2, 3, 4, 5];
$person = ['name' => 'Budi', 'age' => 25];
// Null
$nothing = null;
// Object
$obj = new stdClass();
$obj->name = "Budi";
// Resource
$file = fopen('file.txt', 'r');Fungsi-fungsi untuk memeriksa tipe data dan melakukan type casting.
<?php
// Check types
is_string($var);
is_int($var);
is_float($var);
is_bool($var);
is_array($var);
is_object($var);
is_null($var);
is_numeric($var);
// Get type
gettype($var);
// Type casting
$str = (string) 123;
$int = (int) "123";
$float = (float) "99.99";
$bool = (bool) 1;
$array = (array) $obj;Manipulasi dan operasi pada string dalam PHP.
Operasi-operasi dasar pada string seperti concatenation dan interpolation.
<?php
// Concatenation
$fullName = $firstName . " " . $lastName;
$text = "Hello" . " " . "World";
// String interpolation (double quotes)
$name = "Budi";
echo "Hello, $name";
echo "Hello, {$name}";
// Heredoc
$text = <<<EOT
Multi-line string
Variables: $name
EOT;
// Nowdoc (tanpa parsing variable)
$text = <<<'EOT'
Variables won't be parsed: $name
EOT;Fungsi-fungsi built-in PHP untuk memanipulasi string.
<?php
$str = "Hello World";
// Length
strlen($str); // 11
// Position
strpos($str, "World"); // 6
strrpos($str, "o"); // 7 (last occurrence)
// Case
strtoupper($str); // HELLO WORLD
strtolower($str); // hello world
ucfirst($str); // Hello world
ucwords($str); // Hello World
// Substring
substr($str, 0, 5); // Hello
substr($str, 6); // World
// Replace
str_replace("World", "PHP", $str); // Hello PHP
str_ireplace("world", "PHP", $str); // Case-insensitive
// Trim
trim(" hello "); // "hello"
ltrim(" hello"); // "hello"
rtrim("hello "); // "hello"
// Split & Join
explode(" ", $str); // ["Hello", "World"]
implode(", ", $array); // "a, b, c"
// Contains (PHP 8+)
str_contains($str, "World"); // true
str_starts_with($str, "Hello"); // true
str_ends_with($str, "World"); // trueStruktur data untuk menyimpan koleksi nilai dalam PHP.
Berbagai cara untuk membuat array dalam PHP.
<?php
// Indexed array
$fruits = ["Apple", "Banana", "Orange"];
$numbers = array(1, 2, 3, 4, 5);
// Associative array
$person = [
"name" => "Budi",
"age" => 25,
"city" => "Jakarta"
];
// Multi-dimensional array
$users = [
["name" => "Budi", "age" => 25],
["name" => "Ani", "age" => 22]
];Fungsi-fungsi penting untuk memanipulasi dan bekerja dengan array.
<?php
$arr = [1, 2, 3, 4, 5];
// Add elements
array_push($arr, 6); // Add to end
$arr[] = 6; // Shorthand
array_unshift($arr, 0); // Add to beginning
// Remove elements
array_pop($arr); // Remove last
array_shift($arr); // Remove first
// Count
count($arr); // 5
sizeof($arr); // Alias of count
// Check existence
in_array(3, $arr); // true
array_key_exists("name", $person); // true
isset($person["name"]); // true
// Merge
array_merge($arr1, $arr2);
[...$arr1, ...$arr2]; // Spread operator
// Slice & Splice
array_slice($arr, 1, 3); // Get portion
array_splice($arr, 1, 2, [10, 20]); // Remove & insert
// Search
array_search("Banana", $fruits); // Return key
array_keys($person); // ["name", "age", "city"]
array_values($person); // ["Budi", 25, "Jakarta"]
// Sort
sort($arr); // Ascending
rsort($arr); // Descending
asort($arr); // Sort preserving keys
ksort($arr); // Sort by keys
// Map, Filter, Reduce
array_map(fn($n) => $n * 2, $arr);
array_filter($arr, fn($n) => $n > 2);
array_reduce($arr, fn($carry, $item) => $carry + $item, 0);
// PHP 8.4: New array functions
array_find($arr, fn($n) => $n > 3); // Find first match
array_find_key($arr, fn($n) => $n > 3); // Find key
array_any($arr, fn($n) => $n > 3); // Check if any match
array_all($arr, fn($n) => $n > 0); // Check if all matchStruktur kontrol untuk mengatur alur eksekusi program.
Kondisional if-else dan operator ternary dalam PHP.
<?php
if ($age >= 18) {
echo "Dewasa";
} elseif ($age >= 13) {
echo "Remaja";
} else {
echo "Anak-anak";
}
// Ternary
$status = $age >= 18 ? "Dewasa" : "Belum dewasa";
// Null coalescing
$name = $_GET['name'] ?? 'Guest';
// Null coalescing assignment (PHP 7.4+)
$name ??= 'Default';Struktur switch sebagai alternatif untuk if-else yang lebih readable.
<?php
switch ($day) {
case 'Monday':
echo "Senin";
break;
case 'Friday':
echo "Jumat";
break;
default:
echo "Hari lain";
}
// Match expression (PHP 8+)
$result = match($day) {
'Monday' => 'Senin',
'Friday' => 'Jumat',
default => 'Hari lain'
};<?php
// For loop
for ($i = 0; $i < 10; $i++) {
echo $i;
}
// While loop
$i = 0;
while ($i < 10) {
echo $i;
$i++;
}
// Do-while loop
do {
echo $i;
$i++;
} while ($i < 10);
// Foreach loop
foreach ($fruits as $fruit) {
echo $fruit;
}
foreach ($person as $key => $value) {
echo "$key: $value";
}
// Break & Continue
for ($i = 0; $i < 10; $i++) {
if ($i == 5) break;
if ($i == 3) continue;
echo $i;
}<?php
// Basic function
function greet($name) {
return "Hello, $name";
}
// Default parameters
function greet($name = "Guest") {
return "Hello, $name";
}
// Type declarations
function add(int $a, int $b): int {
return $a + $b;
}
// Multiple return types (PHP 8+)
function getValue(): int|string {
return rand(0, 1) ? 42 : "forty-two";
}
// Nullable types
function getName(): ?string {
return null;
}
// Void return
function logMessage(string $message): void {
echo $message;
}<?php
// Short syntax
$double = fn($n) => $n * 2;
// Auto-capture variables
$multiplier = 3;
$triple = fn($n) => $n * $multiplier;
// With array functions
array_map(fn($n) => $n * 2, $numbers);<?php
$func = 'greet';
$func('Budi'); // Call greet('Budi')
// Anonymous function
$greet = function($name) {
return "Hello, $name";
};
// Closure with use
$multiplier = 3;
$multiply = function($n) use ($multiplier) {
return $n * $multiplier;
};<?php
class Person {
// Properties
public string $name;
private int $age;
protected string $email;
// Constructor
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
// Methods
public function greet(): string {
return "Hello, I'm {$this->name}";
}
// Getter
public function getAge(): int {
return $this->age;
}
// Setter
public function setAge(int $age): void {
$this->age = $age;
}
}
// Create object
$person = new Person("Budi", 25);
echo $person->greet();<?php
class User {
// Property dengan hooks
public string $name {
// Get hook
get => strtoupper($this->name);
// Set hook
set => ucfirst($value);
}
public int $age {
set {
if ($value < 0) {
throw new ValueError("Age must be positive");
}
$this->age = $value;
}
}
}
$user = new User();
$user->name = "budi"; // Stored as "Budi"
echo $user->name; // Output: BUDI<?php
class Animal {
protected string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function makeSound(): string {
return "Some sound";
}
}
class Dog extends Animal {
public function makeSound(): string {
return "Woof!";
}
public function wagTail(): void {
echo "{$this->name} is wagging tail";
}
}
$dog = new Dog("Buddy");
echo $dog->makeSound(); // Woof!<?php
// Interface
interface Drivable {
public function drive(): void;
public function stop(): void;
}
class Car implements Drivable {
public function drive(): void {
echo "Driving...";
}
public function stop(): void {
echo "Stopping...";
}
}
// Trait
trait Loggable {
public function log(string $message): void {
echo "[LOG] $message";
}
}
class User {
use Loggable;
}
$user = new User();
$user->log("User created");<?php
abstract class Shape {
abstract public function area(): float;
public function describe(): string {
return "This is a shape";
}
}
class Circle extends Shape {
private float $radius;
public function __construct(float $radius) {
$this->radius = $radius;
}
public function area(): float {
return pi() * $this->radius ** 2;
}
}<?php
class Status {
public const string ACTIVE = 'active';
public const string INACTIVE = 'inactive';
public const int MAX_RETRY = 3;
}<?php
class User {
// Public read, private write
public private(set) string $username;
public function __construct(string $username) {
$this->username = $username;
}
}
$user = new User("budi");
echo $user->username; // OK
// $user->username = "ani"; // Error!<?php
// Tanpa null safe
$country = null;
if ($user !== null) {
$country = $user->getAddress()?->getCountry();
}
// Dengan null safe
$country = $user?->getAddress()?->getCountry();<?php
function createUser(
string $name,
int $age,
string $email = '',
bool $active = true
) {
// ...
}
// Skip parameters
createUser(
name: "Budi",
age: 25,
active: false
);<?php
$result = match($status) {
'pending' => 'Waiting',
'approved', 'confirmed' => 'Accepted',
'rejected' => 'Denied',
default => 'Unknown'
};
// Dengan kondisi
$fee = match(true) {
$age < 18 => 0,
$age < 65 => 10,
default => 5
};<?php
#[Route('/api/users')]
class UserController {
#[Get]
#[Cached(seconds: 3600)]
public function index() {
// ...
}
}<?php
enum Status {
case Pending;
case Approved;
case Rejected;
}
enum Status: string {
case Pending = 'pending';
case Approved = 'approved';
case Rejected = 'rejected';
public function label(): string {
return match($this) {
self::Pending => 'Menunggu',
self::Approved => 'Disetujui',
self::Rejected => 'Ditolak',
};
}
}
$status = Status::Pending;
echo $status->value; // 'pending'
echo $status->label(); // 'Menunggu'<?php
class User {
public function __construct(
public readonly string $id,
public readonly string $name,
) {}
}
$user = new User('123', 'Budi');
// $user->name = 'Ani'; // Error!<?php
readonly class Config {
public function __construct(
public string $apiKey,
public string $apiUrl,
) {}
}<?php
try {
// Code yang mungkin error
$result = riskyOperation();
} catch (Exception $e) {
// Handle error
echo "Error: " . $e->getMessage();
} finally {
// Always execute
cleanup();
}
// Multiple catch
try {
// ...
} catch (TypeError $e) {
echo "Type error";
} catch (ValueError $e) {
echo "Value error";
} catch (Exception $e) {
echo "General error";
}<?php
class UserNotFoundException extends Exception {}
function findUser($id) {
if (!userExists($id)) {
throw new UserNotFoundException("User not found");
}
return getUser($id);
}
try {
$user = findUser(123);
} catch (UserNotFoundException $e) {
echo $e->getMessage();
}<?php
#[\Deprecated(
message: "Use newMethod() instead",
since: "1.5.0"
)]
function oldMethod() {
// ...
}<?php
// Read entire file
$content = file_get_contents('file.txt');
// Read as array
$lines = file('file.txt');
// Read with fopen
$file = fopen('file.txt', 'r');
while (!feof($file)) {
$line = fgets($file);
echo $line;
}
fclose($file);<?php
// Write string to file
file_put_contents('file.txt', 'Hello World');
// Append to file
file_put_contents('file.txt', 'More content', FILE_APPEND);
// Write with fopen
$file = fopen('file.txt', 'w');
fwrite($file, 'Hello World');
fclose($file);<?php
// Check existence
file_exists('file.txt');
is_file('file.txt');
is_dir('directory');
// File info
filesize('file.txt');
filemtime('file.txt'); // Last modified time
// Copy, rename, delete
copy('source.txt', 'dest.txt');
rename('old.txt', 'new.txt');
unlink('file.txt'); // Delete
// Directory operations
mkdir('directory');
rmdir('directory');
scandir('directory');<?php
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=mydb',
'username',
'password',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}<?php
// Select
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Prepared statements (prevent SQL injection!)
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();
// Named parameters
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
// Insert
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute([$name, $email]);
$lastId = $pdo->lastInsertId();
// Update
$stmt = $pdo->prepare("UPDATE users SET name = ? WHERE id = ?");
$stmt->execute([$name, $id]);
// Delete
$stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
$stmt->execute([$id]);{
"require": {
"monolog/monolog": "^3.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}# Install dependencies
composer install
# Update dependencies
composer update
# Add package
composer require vendor/package
# Remove package
composer remove vendor/package
# Dump autoload
composer dump-autoload<?php
require 'vendor/autoload.php';
use App\Models\User;
use Monolog\Logger;
$user = new User();
$logger = new Logger('app');<?php
// Always use type declarations
function processUser(User $user): bool {
// ...
}
// Strict types (recommended)
declare(strict_types=1);<?php
// Enable error reporting di development
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Disable di production
error_reporting(0);
ini_set('display_errors', 0);<?php
// Prevent XSS
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
// Prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
// Password hashing
$hash = password_hash($password, PASSWORD_DEFAULT);
$verified = password_verify($password, $hash);
// CSRF protection
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));Login atau daftar akun gratis untuk membaca cheat sheet ini.