Php Classes And Objects Complete Guide
Understanding the Core Concepts of PHP Classes and Objects
PHP Classes and Objects
Defining a Class: A class in PHP serves as a blueprint for creating objects. It encapsulates data properties and functions that manipulate the data, providing a way to structure your code.
class Vehicle {
// Properties
public $color;
protected $brand;
private $model;
// Methods
public function setColor($color) {
$this->color = $color;
}
public function getColor() {
return $this->color;
}
protected function setBrand($brand) {
$this->brand = $brand;
}
protected function getBrand() {
return $this->brand;
}
private function setModel($model) {
$this->model = $model;
}
private function getModel() {
return $this->model;
}
}
- Public: Accessible from anywhere.
- Protected: Accessible within the class and by inheriting classes.
- Private: Accessible only within the class it is declared.
Creating an Object:
Objects are instances of a class. You can create objects using the new
keyword.
$car = new Vehicle();
Setting and Getting Values: To interact with a class’s properties, you typically use its methods.
$car->setColor('Blue');
echo $car->getColor(); // Output: Blue
Constructor Method:
A constructor is a method called when an object is instantiated. It’s defined using the __construct()
magic method.
class Vehicle {
public $color;
protected $brand;
private $model;
public function __construct($color, $brand, $model) {
$this->color = $color;
$this->setBrand($brand);
$this->setModel($model);
}
// Rest of the class methods remain unchanged
}
$car = new Vehicle('Blue', 'Toyota', 'Corolla');
Magic Methods:
PHP has several magic methods that start with double underscores (__
). They perform special operations when specific conditions occur.
__construct()
: Constructor method, called when an object is created.__destruct()
: Destructor method, called when an object is destroyed or script execution ends.__get()
,__set()
: Used to handle getting and setting inaccessible properties.__toString()
: Invoked during string conversion, allows defining object behavior when cast to a string.__invoke()
: Allows an object to be treated like a function.__call()
,__callStatic()
: Triggered when attempting to call an undefined or inaccessible method.
Inheritance:
Classes can inherit properties and methods from a parent class using the extends
keyword.
class Car extends Vehicle {
public function displayInfo() {
echo "Car Color: " . $this->color . "\n";
echo "Car Brand: " . $this->getBrand() . "\n"; // Works because this class inherits from Vehicle
// Cannot access $this->model directly due to private visibility in Vehicle
}
}
$myCar = new Car('Red', 'Honda', 'Civic');
$myCar->displayInfo();
Abstract Classes: An abstract class cannot be instantiated on its own but must be inherited. Such classes often contain one or more abstract methods which do not have a body and must be implemented in the child classes.
abstract class Animal {
abstract protected function makeSound();
public function run() {
echo "Animal is running.";
}
}
class Dog extends Animal {
protected function makeSound() {
echo "Woof Woof!";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: Woof Woof!
$dog->run(); // Output: Animal is running.
Interfaces:
Interfaces declare methods that a class must implement, without defining how these methods should work (method bodies). Use the implements
keyword to inherit from an interface.
interface Playable {
public function play();
}
class Piano implements Playable {
public function play() {
echo "Piano is playing music.";
}
}
$piano = new Piano();
$piano->play(); // Output: Piano is playing music.
Static Properties and Methods: Static properties and methods belong to the class rather than an instance of the class.
class Counter {
public static $count = 0; // Static property
public static function increment() { // Static method
self::$count++;
}
}
Counter::increment();
echo Counter::$count; // Output: 1
self::
keyword refers to the current class within a class context.
Class Constants:
Constants are declared inside a class with the const
keyword and are accessed using the ::
scope resolution operator.
class Product {
const TAX_RATE = 0.07;
public function calculateTax($price) {
return $price * self::TAX_RATE;
}
}
echo Product::TAX_RATE; // Output: 0.07
$product = new Product();
echo $product->calculateTax(100); // Output: 7
Encapsulation: Encapsulation limits the accessibility of certain parts of the code. It keeps the internal state of an object hidden and protected from the outside world, only exposing necessary functionality through public methods.
Polymorphism: Polymorphism allows methods to do different things based on the object it is acting upon. Most commonly seen through method overriding — where a child class redefines the functionality of a method inherited from its parent.
class Animal {
public function speak() {
echo "Some generic animal sound.";
}
}
class Cat extends Animal {
public function speak() {
echo "Meow!";
}
}
$animal = new Animal();
$cat = new Cat();
echo $animal->speak(); // Output: Some generic animal sound.
echo $cat->speak(); // Output: Meow!
Access Modifiers:
- Public: The method or property can be accessed from anywhere.
- Protected: Accessible within the class and all classes derived from it.
- Private: Accessible only within the class it is declared.
Final Keyword: When used before a method, it prevents the method from being overridden in any class which inherits it. When used before a class, it prevents other classes from extending from it.
class Base {
final public function greet() {
echo "Hi from Base class.";
}
}
class Derivative extends Base {
// public function greet() {} // Error: Cannot override final method from Base
}
Traits: Traits provide a mechanism for code reuse in single inheritance languages like PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
trait MyTrait {
public function sayHello() {
echo "Hello from Trait!";
}
}
class MyClass {
use MyTrait;
}
$obj = new MyClass();
$obj->sayHello(); // Output: Hello from Trait!
Namespace:
Namespaces help avoiding name collisions when combining libraries and projects developed independently. Each namespace begins with the namespace
keyword.
namespace Vehicles;
class Motorcycle {
// Motorcycle class details
}
// Usage
$motorcycle = new Vehicles\Motorcycle();
Autoloading Classes:
PHP provides mechanisms for automatically loading classes using spl_autoload_register and require_once
.
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
$obj = new MyClass(); // MyClass.php will be loaded automatically
Reflection API: PHP provides a Reflection API that gives you information about methods, properties, and other aspects of PHP classes and objects at runtime.
$reflectionClass = new \ReflectionClass('Vehicle');
$properties = $reflectionClass->getProperties();
foreach($properties as $property) {
echo $property->getName() . "\n";
}
Reflection API Example: Retrieve all properties, including their visibilities and values of an object.
$vehicle = new Vehicle('Gray', 'Ford', 'Mustang');
$reflectionVehicle = new ReflectionObject($vehicle);
$properties = $reflectionVehicle->getProperties();
foreach ($properties as $prop) {
if (!$prop->isPublic()) {
$prop->setAccessible(true);
}
echo $prop->getName() . ": " . $prop->getValue($vehicle) . "\n";
}
// Output:
// color: Gray
// brand: Ford
// model: Mustang
Error Handling:
PHP provides built-in error handling mechanisms for managing exceptions when they occur. Classes can throw exceptions and catch them using try/catch
blocks.
class User {
private $name;
public function setName($name) {
if (!is_string($name)) {
throw new Exception("Invalid name format.");
}
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
try {
$usr = new User();
$usr->setName(123); // Not a string
} catch(Exception $e) {
echo "Exception Caught: " . $e->getMessage();
}
// Output: Exception Caught: Invalid name format.
Important Information:
- PHP treats variables and objects differently. When assigning a variable to another variable or passing it to a function, PHP copies the variable. However, objects are treated as references, meaning both variables will point to the same instance.
- Classes can be documented using DocBlock annotations, assisting tools like IDEs in generating code documentation and improving navigation.
- Magic methods should be used judiciously to avoid obfuscating your code.
- OOP principles such as Encapsulation, Inheritance, Polymorphism, and Abstraction should be adhered to in designing your application architecture.
Online Code run
Step-by-Step Guide: How to Implement PHP Classes and Objects
Example 1: Defining a Simple Class
Step-by-Step Guide:
- Define a class using the
class
keyword. - Declare properties within the class.
- Create methods to manipulate these properties.
<?php
// Step 1: Define a new class named 'Car'
class Car {
// Step 2: Declare properties
public $brand;
public $color;
// Step 3: Create a method to describe the car
public function describe() {
return "This car is a $this->color $this->brand";
}
}
// Create an object from the Car class
$myCar = new Car(); // Instantiation
// Set the values of the properties
$myCar->brand = "Toyota";
$myCar->color = "Red";
// Call the method to get a description of the car
echo $myCar->describe(); // Output: This car is a Red Toyota
?>
Example 2: Constructor Method
Step-by-Step Guide:
- Define a constructor method
__construct()
within the class. - Initialize properties inside the constructor.
<?php
class Car {
public $brand;
public $color;
// Step 1: Define a constructor method
public function __construct($brand, $color) {
$this->brand = $brand; // Step 2: Initialize brand property
$this->color = $color; // Step 2: Initialize color property
}
public function describe() {
return "This car is a $this->color $this->brand";
}
}
// Create a new car object using the constructor
$yourCar = new Car("Honda", "Blue");
// Call the describe method
echo $yourCar->describe(); // Output: This car is a Blue Honda
?>
Example 3: Private Properties and Getter Methods
Step-by-Step Guide:
- Make properties private using the
private
keyword. - Provide public getter methods to access these properties.
<?php
class Car {
private $brand;
private $color;
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
// Step 1: Create getter for private property 'brand'
public function getBrand() {
return $this->brand;
}
// Step 1: Create getter for private property 'color'
public function getColor() {
return $this->color;
}
public function describe() {
return "This car is a {$this->getColor()} {$this->getBrand()}";
}
}
// Create a new Car object
$anotherCar = new Car("Ford", "Green");
// Get properties via getters
echo "Brand: " . $anotherCar->getBrand(); // Output: Brand: Ford
echo "\n";
echo "Color: " . $anotherCar->getColor(); // Output: Color: Green
echo "\n";
echo $anotherCar->describe(); // Output: This car is a Green Ford
?>
Example 4: Static Members
Step-by-Step Guide:
- Declare static properties or methods using the
static
keyword. - Access static properties with the
::
operator.
<?php
class Car {
private $brand;
private $color;
// Step 1: Define a static property
static $totalCars = 0;
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
// Increase count every time a new car is created
Car::$totalCars++; // Accessing static property
}
// Step 1: Define a static method
static function getTotalCars() {
// Return the value of the static property
return Car::$totalCars;
}
}
$car1 = new Car("Chevrolet", "Black");
$car2 = new Car("BMW", "White");
// Step 2: Access the total number of cars via the static method
echo "Total Cars: " . Car::getTotalCars(); // Output: Total Cars: 2
?>
Example 5: Inheritance
Step-by-Step Guide:
- Define a parent class.
- Define a child class that extends the parent class.
- Use the
extends
keyword to make inheritance happen.
<?php
// Step 1: Define the parent class
class Vehicle {
protected $type;
public function __construct($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
// Step 2: Create a child class which extends the parent class
class Car extends Vehicle {
private $brand;
private $color;
public function __construct($brand, $color) {
parent::__construct("Car"); // Step 3: Call the parent constructor
$this->brand = $brand;
$this->color = $color;
}
public function describe() {
return "This vehicle is a {$this->getType()} from {$this->brand} in color {$this->color}";
}
}
// Create a new Car object
$newCar = new Car("Audi", "Silver");
// Call the describe method
echo $newCar->describe(); // Output: This vehicle is a Car from Audi in color Silver
?>
Example 6: Interfaces
Step-by-Step Guide:
- Define an interface using the
interface
keyword. - Declare methods within the interface that must be implemented by any class using it.
- Implement the interface using the
implements
keyword.
<?php
// Step 1: Create an interface 'Drivable'
interface Drivable {
// Step 2: Declare methods - these need implementation by any class that implements this interface
public function drive();
public function stop();
}
// Step 3: Implement the interface in a class
class Car implements Drivable {
private $brand;
private $color;
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
public function drive() {
return "The {$this->brand} car is now driving.";
}
public function stop() {
return "The {$this->brand} car has stopped.";
}
}
// Create a new Car object
$aCar = new Car("Mercedes", "Black");
// Use the methods defined in the interface
echo $aCar->drive(); // Output: The Mercedes car is now driving.
echo "\n";
echo $aCar->stop(); // Output: The Mercedes car has stopped.
?>
Example 7: Abstract Classes
Step-by-Step Guide:
- Define an abstract class using the
abstract
keyword. - Declare abstract methods within the class that must be implemented by any non-abstract child class.
Top 10 Interview Questions & Answers on PHP Classes and Objects
Top 10 Questions and Answers on PHP Classes and Objects
1. What is a Class in PHP?
Answer Example:
class Car {
public $color;
private $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function displayInfo() {
return "Car model: " . $this->model . " is " . $this->color . ".";
}
}
In this example, Car
is a class with two properties, $color
and $model
. The property $model
is marked as private
, meaning it cannot be accessed directly from outside the class. The displayInfo
method reveals information about the car's model and color.
2. What is an Object in PHP?
An object in PHP is an instance of a class. When you instantiate a class, you create an object using the new
keyword. An object stores the state of the class and uses the behaviors defined within its class methods.
Answer Example:
$myCar = new Car("red", "Toyota Camry");
echo $myCar->displayInfo(); // Outputs: Car model: Toyota Camry is red.
Here, $myCar
is an object created from the Car
class with specific values for its properties.
3. How do you define a Constructor in PHP?
A constructor in PHP is a special type of method that is automatically called when a class is instantiated. Constructors are declared using the __construct()
magic method and are primarily used to initialize object properties.
Answer Example:
class Vehicle {
public $type;
public $year;
public function __construct($type, $year) {
$this->type = $type;
$this->year = $year;
}
public function getIntroduction() {
return "This vehicle is a " . $this->type . " made in " . $this->year;
}
}
$bike = new Vehicle('motorcycle', 2021);
echo $bike->getIntroduction(); // Outputs: This vehicle is a motorcycle made in 2021.
The Vehicle
class has a constructor that sets the $type
and $year
properties of a new object to the values provided during instantiation.
4. What are the Access Modifiers in PHP and how do they differ?
PHP supports three access modifiers for class properties and methods: public
, protected
, and private
.
- Public: Accessible from anywhere - inside the class, outside the class, and through derived classes.
- Protected: Accessible only within the class itself and by its derived classes.
- Private: Accessible only within the class itself. It restricts the visibility of a class member to the class declaring them.
Answer Example:
class Product {
public $name; // Public property
protected $price; // Protected property
private $discount; // Private property
public function __construct($name, $price, $discount) {
$this->name = $name;
$this->price = $price;
$this->discount = $discount;
}
protected function calculateDiscount() {
return $this->price * ($this->discount / 100);
}
public function getPriceAfterDiscount() {
return $this->price - $this->calculateDiscount();
}
}
5. What is Inheritance in PHP and how do you implement it?
Inheritance allows a child class to inherit all properties and methods from a parent class, promoting code reusability and organization. To define a child class, use the extends
keyword.
Answer Example:
class ElectricVehicle extends Vehicle {
public $batteryLife;
public function __construct($type, $year, $batteryLife) {
parent::__construct($type, $year);
$this->batteryLife = $batteryLife;
}
public function getBatteryDetails() {
return parent::getIntroduction() . " with battery life of " . $this->batteryLife . " hours.";
}
}
$teslaModelX = new ElectricVehicle('car', 2022, 600);
echo $teslaModelX->getBatteryDetails(); // Outputs: This vehicle is a car made in 2022 with battery life of 600 hours.
The ElectricVehicle
class inherits properties and methods from Vehicle
and can access or override them.
6. Can a PHP class inherit multiple parents? Why or why not?
In PHP, a class cannot extend multiple parent classes directly. However, you can achieve similar functionality using interfaces (interface
) and traits (trait
).
- Interfaces: Define methods that must be implemented by a class but do not provide their implementation.
- Traits: Allow methods to be reused in unrelated classes without multiple inheritance.
Answer Example with Trait:
trait Speedometer {
public function calculateSpeed() {
return "Speedometer calculation logic here";
}
}
class Motorboat {
use Speedometer; // Using trait
public function startEngine() {
return "Motorboat engine started.";
}
}
$boat = new Motorboat();
echo $boat->startEngine(); // Outputs: Motorboat engine started.
echo $boat->calculateSpeed(); // Outputs: Speedometer calculation logic here
Using Speedometer
trait allows Motorboat
class to have calculateSpeed()
method without inheriting a parent class.
7. What is Polymorphism in PHP and how do you use it?
Polymorphism is a feature in OOP that allows methods with the same name to have different behaviors based on the object that calls them. It is commonly implemented through method overriding and interfaces.
Answer Example with Method Overriding:
class Truck extends Vehicle {
public function getIntroduction() {
return "Heavy-duty vehicle: " . $this->type . " manufactured in " . $this->year;
}
}
$myTruck = new Truck('truck', 2019);
echo $myTruck->getIntroduction(); // Outputs: Heavy-duty vehicle: truck manufactured in 2019
The getIntroduction
method has been overridden in the Truck
class to modify its behavior.
8. Explain Encapsulation in PHP with an Example.
Encapsulation is the concept of wrapping data (properties) and code acting on the data (methods) into a single unit and controlling access to that data. This enhances security and data integrity.
Answer Example:
class Account {
private $balance;
public function __construct($initialBalance) {
if ($initialBalance > 0) {
$this->balance = $initialBalance;
} else {
throw new Exception("Initial balance must be greater than zero.");
}
}
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
} else {
throw new Exception("Deposit amount must be positive.");
}
}
public function withdraw($amount) {
if ($amount > 0 && $this->balance >= $amount) {
$this->balance -= $amount;
} else {
throw new Exception("Invalid withdrawal.");
}
}
public function getBalance() {
return "Your account balance is " . $this->balance . ".";
}
}
$myAccount = new Account(100);
echo $myAccount->getBalance(); // Outputs: Your account balance is 100.
The balance property is private, and can only be changed via the deposit()
or withdraw()
methods, ensuring the balance is always valid.
9. What is a Static Property/Method in PHP?
Static properties and methods belong to the class, not its instances. They can be called using the class name prefixed with a double colon (::
) without needing to create an object.
Answer Example:
class Math {
static public $piValue = 3.14159;
static public function calculateAreaOfCircle($radius) {
return self::$piValue * pow($radius, 2);
}
}
echo Math::$piValue; // Outputs: 3.14159
echo Math::calculateAreaOfCircle(5); // Outputs: 78.53975
The Math
class contains a static property $piValue
and a static method calculateAreaOfCircle()
that uses this property.
10. What is an Abstract Class in PHP and when would you use it?
Abstract classes in PHP cannot be instantiated on their own and are used for defining a common interface for derived classes. They often contain abstract methods that must be implemented by child classes.
Answer Example:
abstract class VehicleBase {
abstract protected function startEngine();
public function stopEngine() {
echo "Engine stopped.";
}
}
class Motorcycle extends VehicleBase {
protected function startEngine() {
echo "Motorcycle's engine started.";
}
}
$motorcycle = new Motorcycle();
$motorcycle->startEngine(); // Outputs: Motorcycle's engine started.
$motorcycle->stopEngine(); // Outputs: Engine stopped.
The VehicleBase
class is abstract and defines an abstract method startEngine()
. Each subclass (like Motorcycle
) must provide its own implementation.
Login to post a comment.