PHP Notes - Functions, Classes, OOP, Files and Directories
1. User-Defined Functions
Functions are reusable blocks of code that allow programmers to organize,
modularize, and simplify large programs. In PHP, user-defined functions
play a crucial role in structuring logic.
Types of functions include:
- Simple User-Defined Functions
- Functions with Arguments
- Functions with Return Values
- Functions with Default Argument Values
- Functions with Dynamic Argument Lists
- Recursive Functions
- Variable Scope inside Functions
Functions allow abstraction of logic, reduce redundancy, and make
debugging easier. They can be invoked multiple times with different inputs,
enabling flexibility.
Simple User-Defined Functions
A function is a block of statements grouped together to perform a specific
task. In PHP, programmers can define their own functions in addition to the
built-in ones. A user-defined function provides a way to encapsulate logic so
that it can be reused at multiple places in a program. This avoids repetition
of code and makes maintenance easier. Once defined, a function can be
invoked any number of times, which reduces redundancy and simplifies
debugging.
Functions with Arguments
Functions often require inputs to perform their tasks. These inputs are called
arguments or parameters. Arguments allow the same function to work with
different data. For example, a mathematical function may need two numbers
to calculate their sum. By passing different values as arguments, the function
becomes versatile. PHP allows multiple arguments, and they can be passed
in order.
Functions with Return Values
In addition to performing tasks, functions may also return results to the point
from which they were called. A return value makes it possible for the
function to act like a computation tool. This return mechanism allows the
function to be embedded into larger expressions and makes code more
powerful and flexible. A function may return simple values like numbers
and strings, or complex data structures like arrays.
Functions with Default Argument Values
Sometimes, not all arguments are required every time a function is called. In
such cases, PHP allows assigning default values to parameters. If the caller
does not provide an argument, the default is used. This reduces the burden
on the caller and makes functions more user-friendly. Default arguments are
especially useful when most of the function’s work is based on common
values, and only in some cases do programmers need to override them.
Functions with Dynamic Argument Lists
PHP also supports functions that can accept a variable number of arguments.
This feature allows functions to be more general and adaptable. It is
particularly helpful when the exact number of inputs is not known in
advance. For example, a function designed to calculate the sum of numbers
may need to handle two, three, or even more numbers. Dynamic argument
lists make the function flexible enough to manage these situations without
rewriting its definition.
Recursive Functions
Recursion is a programming technique where a function calls itself, either
directly or indirectly. Recursive functions are especially useful for solving
problems that can be broken down into smaller sub-problems of the same
type. Classic applications include mathematical calculations like factorial or
Fibonacci series, as well as data-processing tasks such as traversing trees or
directories. Recursive functions must always have a base condition to
prevent infinite loops.
Variable Scope inside Functions
Scope determines where a variable can be accessed in a program. PHP has
local, global, and static scopes. Local variables exist only within the function
in which they are declared, while global variables exist outside and must be
explicitly imported into a function. Static variables preserve their values
between multiple calls of the same function. Understanding scope is crucial
to avoid conflicts and unexpected behavior when using functions.
2. Classes, Objects, and Member Functions
Classes are blueprints or templates for creating objects. An object is an
instance of a class, and it encapsulates both data (properties) and behavior
(methods).
Key elements:
- Class: Defines structure and behavior.
- Object: Instance created from a class.
- Properties: Variables inside a class.
- Member Functions (Methods): Functions inside a class used to manipulate
properties.
Using classes provides modularity, abstraction, and reusability. Member
functions allow objects to interact with their internal data, enforcing
encapsulation.
Class
A class is a programmer-defined blueprint or template that specifies how
objects should be created and how they should behave. It combines variables
and functions into a single structure. The variables are referred to as
properties, while the functions are called methods. A class allows developers
to model real-world entities in a program.
Object
An object is a specific instance created from a class. Each object has its own
copy of properties defined by the class but shares the behavior described by
methods. Objects interact with each other by sending and receiving
messages (method calls). In PHP, multiple objects can be created from the
same class, each maintaining its own state.
Properties
Properties are variables defined inside a class. They store the data or state of
an object. For example, in a class representing a car, properties might
include color, model, and engine capacity. Properties define the attributes of
objects and can be public, private, or protected depending on visibility.
Member Functions (Methods)
Member functions are the actions or behaviors that an object can perform.
They are defined inside a class and are used to manipulate object properties
or carry out tasks related to the object. For instance, in the car class, methods
might include startEngine() or applyBrakes(). Member functions ensure
encapsulation, meaning that internal data can only be accessed or modified
in controlled ways.
Benefits of Classes and Objects
Classes and objects provide abstraction, modularity, and reusability. They
make complex systems easier to design and maintain. Encapsulation ensures
that changes to internal implementation do not affect other parts of the
program. In addition, classes allow inheritance, which extends functionality
without rewriting code.
Constructors
The constructor method inside a class is called automatically on each newly
created object. Note that defining a constructor is not mandatory. However,
if present, it is suitable for any initialization that the object may need before
it is used.
You can pass as many as arguments you like into the constructor function.
The __construct() function doesn't have any return value.
Destructors
PHP also has a __destructor() function. It implements a destructor concept
similar to that of other object-oriented languages, as in C++. The destructor
method will be called as soon as there are no other references to a particular
object.
he __destruct() function doesn't have any parameters, neither does it have
any return value. The fact that the __destruct() function is automatically
called when any object goes out of scope, can be verified by putting
var_dump($this) inside the function.
As mentioned above, $this carries the reference to the calling object, the
dump shows that the member variables are set to NULL
3. Advanced OOP Concepts
Advanced Object-Oriented Programming (OOP) concepts in PHP enhance
class-based design by supporting features such as constructors, destructors,
inheritance, and visibility settings.
Main concepts:
- Constructors and Destructors: Special methods used for initialization and
cleanup.
- Inheritance: Mechanism for creating new classes from existing ones.
- Visibility (public, private, protected): Controls accessibility of properties
and methods.
- Encapsulation: Bundling data and methods together.
- Polymorphism: Ability for methods to take different forms.
- Interfaces and Abstract Classes: Define contracts for implementation.
These concepts allow scalable, maintainable, and secure PHP applications.
inheritance
Inheritance allows one class to acquire the properties and methods of another
class. The existing class is called the parent or base class, while the new
class is called the child or derived class. Inheritance promotes reusability by
allowing programmers to extend functionality without rewriting existing
code. It also supports hierarchical classification of entities.
Visibility (Access Modifiers)
Visibility defines how properties and methods can be accessed:
• Public: Accessible from anywhere in the program.
• Private: Accessible only within the class that defines them.
• Protected: Accessible within the class and by derived classes.
These modifiers help enforce encapsulation and security by
controlling access to internal data.
Encapsulation
Encapsulation is the principle of bundling data and methods together while
restricting direct access to some components. By providing controlled access
through methods, classes prevent unauthorized changes and preserve data
integrity.
Polymorphism
Polymorphism allows the same operation to behave differently depending on
the context. In PHP, polymorphism is achieved through method overriding
in inheritance or through interfaces. This makes code flexible and extensible,
allowing objects of different classes to be treated uniformly.
Interfaces and Abstract Classes
Interfaces define a contract of methods that must be implemented by any
class using them. Abstract classes are partially implemented classes that
cannot be instantiated directly. Both mechanisms allow programmers to
enforce a consistent design across different classes while leaving flexibility
for specific implementations.