Properties and Methods in PHP
Introduction to Properties and Methods
In PHP's Object-Oriented Programming (OOP), properties (also called attributes or fields) and methods (also called functions) are the two fundamental building blocks of classes.
- Properties → Variables that store data within a class
- Methods → Functions that define behavior and operations
Properties in PHP Classes
2.1 Defining Properties
Properties are declared inside a class using visibility modifiers (public, private, protected).
class Product {
// Property declaration
public $name; // Public - accessible anywhere
private $price; // Private - only within this class
protected $discount; // Protected - within this class and child classes
}
2.2 Property Visibility
Modifier | Access Scope |
---|---|
public |
Anywhere (inside/outside class, inherited classes) |
private |
Only within the defining class |
protected |
Within the defining class and child classes |
2.3 Accessing Properties
$product = new Product();
$product->name = "Laptop"; // OK (public)
// $product->price = 999; // Error (private)
// $product->discount = 10; // Error (protected)
2.4 Property Default Values
class User {
public $role = 'guest'; // Default value
private $loggedIn = false;
}
Methods in PHP Classes
3.1 Defining Methods
Methods are functions defined inside a class.
class Calculator {
// Method definition
public function add($a, $b) {
return $a + $b;
}
private function log($message) {
// Private method - only accessible within class
file_put_contents('log.txt', $message);
}
}
3.2 Method Visibility
Same visibility rules as properties:
class Auth {
public function login() { /* ... */ } // Accessible anywhere
private function validate() { /* ... */ } // Only within Auth class
protected function encrypt() { /* ... */ } // Auth and child classes
}
3.3 Calling Methods
$calc = new Calculator();
echo $calc->add(5, 3); // Output: 8
// $calc->log("test"); // Error (private method)
3.4 The $this Keyword
$this
refers to the current object instance:
class Car {
public $model;
public function setModel($model) {
$this->model = $model; // Assign to the object's property
}
public function getModel() {
return $this->model;
}
}
Getter and Setter Methods
4.1 Why Use Getters/Setters?
- Control access to private properties
- Add validation logic
- Maintain encapsulation
4.2 Implementation Example
class BankAccount {
private $balance = 0;
// Setter with validation
public function setBalance($amount) {
if ($amount >= 0) {
$this->balance = $amount;
} else {
throw new Exception("Balance cannot be negative");
}
}
// Getter
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
$account->setBalance(1000);
echo $account->getBalance(); // 1000
// $account->balance = -500; // Error (private)
Static Properties and Methods
5.1 Static Properties
Belong to the class rather than instances.
class Counter {
public static $count = 0;
}
5.2 Static Methods
Can be called without creating an instance.
class Math {
public static function square($num) {
return $num * $num;
}
}
echo Math::square(5); // 25
5.3 Accessing Static Members
// Inside the class
self::$count;
self::methodName();
// Outside the class
ClassName::$property;
ClassName::method();
Magic Methods for Properties
PHP provides special methods to handle property access:
6.1 __get() and __set()
class Magic {
private $data = [];
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$obj = new Magic();
$obj->test = "Hello"; // Calls __set()
echo $obj->test; // Calls __get() → "Hello"
6.2 __isset() and __unset()
class Magic {
// ...
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
}
Practical Example: User Class
class User {
private $username;
private $email;
private static $count = 0;
public function __construct($username, $email) {
$this->username = $username;
$this->setEmail($email);
self::$count++;
}
public function setEmail($email) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->email = $email;
} else {
throw new Exception("Invalid email");
}
}
public function getEmail() {
return $this->email;
}
public static function getCount() {
return self::$count;
}
}
$user1 = new User("john_doe", "john@example.com");
$user2 = new User("jane_doe", "jane@example.com");
echo User::getCount(); // 2
Best Practices
- Encapsulation: Make properties private/protected and use getters/setters
- Single Responsibility: Each method should do one thing
- Meaningful Names: Use clear names for properties and methods
-
Type Declarations: Use PHP type hints for better
code reliability
public function setAge(int $age): void
- Avoid Public Properties: Except for simple data containers (DTOs)
Conclusion
- Properties store object state with controlled visibility
- Methods define object behavior and operations
- Getters/Setters provide controlled access to properties
- Static members belong to the class itself
- Magic methods offer flexible property handling