public / private / protected / static Since: PHP 5(2004)
Keywords that control the access scope of class properties and methods. They implement encapsulation to improve code safety.
Syntax
class ClassName {
public $prop1; // Accessible from anywhere
protected $prop2; // Accessible from the class itself and subclasses
private $prop3; // Accessible from the class itself only
public static $count = 0; // Static property
public const VERSION = '1.0'; // Class constant
public static function staticMethod() {
// Static method. Can be called without an instance.
}
}
Syntax List
| Syntax | Description |
|---|---|
| public | Accessible from anywhere — outside the class, from subclasses, and everywhere else. |
| protected | Accessible only from the class itself and its subclasses. Not accessible from outside the class. |
| private | Accessible only from within the class where it is defined. Not accessible from subclasses either. |
| static | Defines a property or method that can be accessed directly via the class name without creating an instance. |
| const | Defines a constant inside a class. Its value cannot be changed. |
Sample Code
<?php
// Basic usage of access modifiers.
class BankAccount {
public string $owner;
private int $balance;
protected string $bank_name;
public function __construct(string $owner, int $balance, string $bank_name) {
$this->owner = $owner;
$this->balance = $balance;
$this->bank_name = $bank_name;
}
public function get_balance(): int {
return $this->balance; // Access private properties through a method.
}
public function deposit(int $amount): void {
if ($amount > 0) {
$this->balance += $amount;
}
}
}
$account = new BankAccount("Taro", 10000, "Test Bank");
echo $account->owner; // Accessible because it is public.
echo $account->get_balance(); // Outputs "10000".
// echo $account->balance; // Error — balance is private.
// How to use static.
class Counter {
private static int $count = 0;
public static function increment(): void {
self::$count++; // Access static properties with self::.
}
public static function get_count(): int {
return self::$count;
}
}
Counter::increment(); // Can be called without an instance.
Counter::increment();
echo Counter::get_count(); // Outputs "2".
// How to use class constants.
class HttpStatus {
public const OK = 200;
public const NOT_FOUND = 404;
public const SERVER_ERROR = 500;
}
echo HttpStatus::OK; // Outputs "200".
echo HttpStatus::NOT_FOUND; // Outputs "404".
// Combining constructor promotion with access modifiers (PHP 8.0+).
class Config {
public function __construct(
public readonly string $app_name,
private readonly string $secret_key,
protected int $max_retry = 3
) {}
public function get_masked_key(): string {
return str_repeat('*', strlen($this->secret_key) - 4)
. substr($this->secret_key, -4);
}
}
$config = new Config("MyApp", "sk_live_abcdefgh1234");
echo $config->app_name; // Outputs "MyApp".
echo $config->get_masked_key(); // Outputs "****************1234".
// Example of the factory method pattern.
class Logger {
private static ?Logger $instance = null;
private function __construct(
private string $log_file
) {}
public static function getInstance(): Logger {
if (self::$instance === null) {
self::$instance = new self('/var/log/app.log');
}
return self::$instance;
}
public function info(string $message): void {
echo "[INFO] $message\n";
}
}
$logger = Logger::getInstance();
$logger->info("Application started.");
Notes
Access modifiers are the mechanism for implementing encapsulation in a class. As a general rule, it is recommended to make properties private or protected and expose access through public methods only when needed. This makes it easier to change the internal implementation of a class without affecting external code.
static defines properties and methods that do not belong to an instance. It is used in utility functions, the singleton pattern, and factory methods, but avoid overusing it as it can make testing difficult.
For the basics of classes, see class. For inheritance and interfaces, see extends / implements. For defining constants in general, see define() / const.
If you find any errors or copyright issues, please contact us.