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 echoBerbagai 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
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
Berbagai tipe data yang didukung oleh PHP.
<?php
// String
$name = "Budi";
$greeting = 'Hello';
// Integer
$age = 25;
$hex = 0x1A; // Hexadecimal
$binary =
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);
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
Fungsi-fungsi built-in PHP untuk memanipulasi string.
<?php
$str = "Hello World";
// Length
strlen($str); // 11
// Position
strpos($str, "World"); // 6
strrpos
Struktur 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
Fungsi-fungsi penting untuk memanipulasi dan bekerja dengan array.
<?php
$arr = [1, 2, 3, 4,
Struktur 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";
}
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";
<?php
// For loop
for ($i = 0; $i < 10; $i++) {
echo $i;
}
// While loop
$i = 0;
while ($i <
<?php
// Basic function
function greet($name) {
return "Hello, $name";
}
// Default parameters
function greet($name = "Guest") {
return "Hello, $name
<?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 <?php
$func = 'greet';
$func('Budi'); // Call greet('Budi')
// Anonymous function
$greet = function($name) {
return "Hello, $name";
};
// Closure with use
$multiplier =
<?php
class Person {
// Properties
public string $name;
private int $age;
protected string $email;
// Constructor
public function __construct(
<?php
class User {
// Property dengan hooks
public string $name {
// Get hook
get => strtoupper($this->name);
// Set hook
set => ucfirst($value);
}
<?php
class Animal {
protected string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function makeSound
<?php
// Interface
interface Drivable {
public function drive(): void;
public function stop(): void;
}
class Car
<?php
abstract class Shape {
abstract public function area(): float;
public function describe(): string {
return "This is a shape";
}
<?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
<?php
// Tanpa null safe
$country = null;
if ($user !== null) {
$country = $user->getAddress()?->getCountry();
}
// Dengan null safe
$country = $user?-><?php
function createUser(
string $name,
int $age,
string $email = '',
bool $active = true
) {
// ...
}
// Skip parameters
createUser(
name
<?php
$result = match($status) {
'pending' => 'Waiting',
'approved', 'confirmed' => 'Accepted',
'rejected' => 'Denied',
default => 'Unknown'
};
// Dengan kondisi
<?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 =
<?php
class User {
public function __construct(
public readonly string $id,
public readonly string $name,
) {}
}
$user = new User('123', 'Budi'
<?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
<?php
class UserNotFoundException extends Exception {}
function findUser($id) {
if (!userExists($id)) {
throw new UserNotFoundException("User not found");
}
return getUser($id);
<?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');
<?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',
<?php
// Check existence
file_exists('file.txt');
is_file('file.txt');
is_dir('directory');
// File info
filesize('file.txt');
filemtime('file.txt');
<?php
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=mydb',
'username',
'password',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
}
<?php
// Select
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(
{
"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 =