PHP Object-Oriented Programming (OOP) Syntax and Core Concepts
PHP History and Evolution
- Original Scope and Purpose:
- PHP was not originally designed as a complete, general-purpose programming language.
- It was initially intended solely for embedding small fragments of code inside HTML web pages to be executed on the web server.
- Evolution Over Time:
- Due to widespread popularity and demand for expanded features, the language was iteratively built out over time.
- Because features were added incrementally to an engine not initially architected for high-level abstractions, certain features and syntax elements in PHP can appear uniquely structured or slightly unconventional.
Procedural vs. Object-Oriented Programming in PHP
- Procedural Programming Paradigm:
- Functions serve as the central focal point of program structure.
- Focuses primarily on taking input data, executing processing steps on that input, and returning an output.
- Core system behaviors are written as standalone functions.
- A program exists as a sequential collection of function calls.
- Object-Oriented Programming (OOP) Paradigm:
- Data and behavior are bound together inside defined structures called classes.
- A program functions as a collection of operations performed on instantiated instances of classes.
- Classes act as blueprints or templates to represent and model real-world entities inside code.
- Data attributes are referred to as properties, while associated behaviors/functions are referred to as methods.
Modeling Entities with Classes and Objects
- Conceptual Mapping:
- Nouns in system specifications map to classes and objects (e.g.,
Student,Customer,Book,User). - Verbs map to class methods (e.g.,
login,checkAvailability,checkout,return). - Descriptions and attributes map to class properties.
- Nouns in system specifications map to classes and objects (e.g.,
- Modeling Example: Library Book:
- Properties (Data/Attributes):
- Book title
- Publish date
- Genre
- Author
- Number of copies available
- Methods (Behaviors/Functions):
- Checking availability
- Checking out a copy
- Returning a copy
- Properties (Data/Attributes):
- PHP Class Declaration Syntax:
- Defined using the
classkeyword followed by the class identifier and curly braces:php class Book { public $title; public $publishDate; public $genre; public $author; public $copiesAvailable; } - Class attributes are declared as variables using the standard dollar sign (
$) prefix.
- Defined using the
- Object Instantiation:
- Objects are instantiated from a class template using the
newkeyword:php $book1 = new Book();
- Objects are instantiated from a class template using the
- The Object Operator (
->):- PHP uses the object operator
->(hyphen followed by greater-than sign, forming an arrow) to access properties and methods on an object instance. - Property names accessed through
->do not include a dollar sign (e.g.,$book1->title = "The Great Gatsby";). - Do not confuse the object operator
->with dot notation (.) used in other languages, nor with array association syntax (=>).
- PHP uses the object operator
Class Methods and Instance Context
Method Syntax inside Classes:
Methods are declared using the
functionkeyword within the class scope: ```php class Book { public $copiesAvailable;public function checkAvailability() { if ($this->copiesAvailable >= 1) { echo "yes, there's a copy available"; } else { echo "no, there's no copies available"; } }} ```
Method Execution & Rules:
- Method names in PHP are case-insensitive.
$thisKeyword: Provides instance context, referencing the specific instantiated object calling the method.- To access an instance's own property inside a method, call
on the property name). - External method execution links the object instance to the method using the arrow operator:
php $book1->checkAvailability();
Storing Objects in Arrays, Iteration, and Formatted Output
Objects in Arrays:
Once a class is defined, objects instantiated from it can be stored in standard PHP arrays just like scalar variables.
Objects are appended to an array using function calls such as
array_push(): ```php $rowOfBooks = array();$bookObject = new Book(); $bookObject->title = "The Great Gatsby"; array_push($rowOfBooks, $bookObject);
$bookObject = new Book(); $bookObject->title = "1984"; array_push($rowOfBooks, $bookObject); ```
Inspecting Objects with
var_dump()and HTML<pre>Tags:- The built-in
var_dump()function prints structured details about variables and object instances. - HTML
<pre>(preformatted text) tags prevent web browsers from collapsing white space, rendering structured dumps across multiple lines raw as formatted in code.
- The built-in
Iterating Arrays of Objects:
- Array element objects can be traversed using a
foreachloop:php foreach ($rowOfBooks as $item) { echo $item->title; $item->checkAvailability(); }
- Array element objects can be traversed using a
Access Modifiers and Encapsulation
- PHP Access Modifiers:
public: Accessible from anywhere—outside the object, within internal methods, and through child classes.private: Accessible only from inside the specific class that defines the property or method.protected: Accessible from inside the defining class and any classes derived (inherited) from that class.
- Encapsulation Best Practices:
- Properties should generally be set to
privateto safeguard internal state against unvalidated external changes. - Controlled access is provided through public getter and setter methods.
- Read-Only Access: Creating a getter method without a corresponding setter method creates a read-only property.
- Data Validation: Setter methods allow validation logic to enforce formatted and expected data structures before modifying property state.
- Public Risk: If properties are declared
public, access control is entirely lost, allowing external execution logic to set arbitrary values.
- Properties should generally be set to
Object Initialization via Constructors
- Constructor Method (
__construct):- A special initialization method designated by two leading underscores followed by
construct(__construct). - Executes automatically upon object creation via
new. - Accepts parameters passed at instantiation time to initialize internal properties.
- Can perform dynamic calculations or state alterations during instantiation (e.g., auto-incrementing tracking IDs).
- A special initialization method designated by two leading underscores followed by
Detailed Implementation Examples
Food Class Implementation (ID Auto-Incrementing): ```php class Food { public $name; public $id; public $protein; public $energy; public $fat; public $carb;
public function __construct($name, $protein, $energy, $fat, $carb) { global $foodCount; $this->name = $name; $this->protein = $protein; $this->energy = $energy; $this->fat = $fat; $this->carb = $carb; $this->id = $foodCount; $foodCount++; }}
$foodCount = 0; $samosa = new Food("Samosa", 3.5, 250, 12, 30); $tiramisu = new Food("Tiramisu", 4.0, 450, 22, 55); $Dumpling = new Food("Dumpling", 8.0, 300, 10, 35); ```
- Initializes dynamic unique numerical IDs () by tracking state across instantiations.
User Security Class (Password Salt Encryption and Encapsulation): ```php class User { private $username; private $hashPassword; private $salt;
public function setUsername($username) { $this->username = $username; } public function getUsername() { return $this->username; } public function setPassword($password) { $this->salt = random_bytes(16); password, $this->salt); } public function checkPassword($password) { if (crypt($password, $this->salt) === $this->hashPassword) { return true; } return false; }} ```
- Encapsulation Checks:
$user1 = new User();$user1->setUsername("Stan");$user1->setPassword("php123");- Checking an incorrect string (e.g., "bare password") returns
false("no match"). - Checking the exact password "php123" returns
true("yes"). - Attempting to directly access or echo
$user1->usernamefrom external script scope produces no output because the property isprivate.
- Encapsulation Checks:
Object Reference Assignment vs. Object Cloning: ```php class City { public $name; public $population;
public function __construct($name, $population) { $this->name = $name; $this->population = $population; } public function incrementPopulation($amount) { $this->population += $amount; }}
class Country { public $name; public $capital;
public function __construct($name, $capital) { $this->name = $name; $this->capital = $capital; }} ```
- Reference Binding Behavior:
$Dunedin = new City("Dunedin", 130000);$city = $Dunedin;- Calling
city->incrementPopulation(200);alters the same underlying object instance. - Both
citypoint to the identical object, resulting in a total combined population increase of .
- Independent Object Cloning:
$Blenheim = new City("Blenheim", 26400);$city2 = clone $Blenheim;- Calling
Blenheim->populationto (). - Calling
city2->populationto (). - The
clonekeyword creates an explicit, separate instance duplicate in memory.
- Class Composition / Nesting:
$country = new Country("New Zealand", $Dunedin);- Nests an instance of the
Cityclass directly inside the$capitalproperty of aCountryobject instance.
- Reference Binding Behavior: