Object-Oriented Programming --- Classes & Objects
⏱ 20 min read read
Key OOP Concepts:
class --- a blueprint that defines properties and methods
object --- an instance created from a class with new
property --- a variable that belongs to a class
\_\_construct --- constructor method, called on new ClassName()
method --- a function inside a class
$this --- refers to the current object (like Java's this)
Access Modifiers:
public --- accessible from anywhere
protected --- accessible from this class and subclasses
private --- accessible only from this class
Constructor Promotion (PHP 8.0+):
A powerful shorthand that declares and assigns properties in one step.
// Traditional way:
class Point {
public float $x;
public float $y;
public function \_\_construct(float $x, float $y) {
$this->x = $x;
$this->y = $y;
}
}
// Constructor promotion (PHP 8+):
class Point {
public function \_\_construct(
public float $x,
public float $y
) {} // That's it! Properties declared AND assigned.
}
Magic Methods:
\_\_construct() --- called on object creation
\_\_toString() --- called when object is converted to string (like
Python's \_\_str\_\_)
\_\_get() / \_\_set() --- property access interception
PHP uses $this->property (arrow ->) to access properties, NOT
$this.property
Public properties can be set directly: $obj->name = "Alice";
Use getters/setters or typed properties (PHP 7.4+) for validation.
class --- a blueprint that defines properties and methods
object --- an instance created from a class with new
property --- a variable that belongs to a class
\_\_construct --- constructor method, called on new ClassName()
method --- a function inside a class
$this --- refers to the current object (like Java's this)
Access Modifiers:
public --- accessible from anywhere
protected --- accessible from this class and subclasses
private --- accessible only from this class
Constructor Promotion (PHP 8.0+):
A powerful shorthand that declares and assigns properties in one step.
// Traditional way:
class Point {
public float $x;
public float $y;
public function \_\_construct(float $x, float $y) {
$this->x = $x;
$this->y = $y;
}
}
// Constructor promotion (PHP 8+):
class Point {
public function \_\_construct(
public float $x,
public float $y
) {} // That's it! Properties declared AND assigned.
}
Magic Methods:
\_\_construct() --- called on object creation
\_\_toString() --- called when object is converted to string (like
Python's \_\_str\_\_)
\_\_get() / \_\_set() --- property access interception
PHP uses $this->property (arrow ->) to access properties, NOT
$this.property
Public properties can be set directly: $obj->name = "Alice";
Use getters/setters or typed properties (PHP 7.4+) for validation.
Log in to track your progress and earn badges as you complete lessons.
Log In to Track Progress