Guide
PHP Functions and Object Oriented Programming Concepts
Understand PHP functions, parameters, return values, classes, objects, inheritance, interfaces and traits in plain language for beginners.
Key takeaways
- A function is a named, reusable block of instructions that takes parameters and can return a value; keep each one small with a single job.
- A class is a blueprint, and an object is an instance of it with its own values.
- Public members are open to all code, protected members to the class and its children, and private members to the class only.
- An interface is a contract of methods; a trait reuses a group of methods across unrelated classes.
- Namespaces prevent name clashes, and exceptions keep error handling separate from normal logic.
Why functions and objects matter
As programs grow, repeating the same instructions in many places becomes a burden. Functions let you name a piece of work and reuse it. Object oriented programming goes further by grouping data and behaviour together into objects. Both ideas keep code organised, testable and easier to change. This guide explains them in prose, so that the concepts are clear before you read any listing.
What is a function in PHP?
A function is a named block of instructions that you can call whenever needed. It can receive inputs, called parameters, and it can give back a result, called a return value. A function that calculates the total price with tax, formats a date for display, or checks whether an email looks valid is a typical example.
Good functions are small and have one clear job. If you struggle to name a function without using the word and, it probably does too much. A useful guideline is that a function should fit on one screen and should be understandable without scrolling.
Parameters and defaults
Parameters are the values a function needs from outside. PHP lets you give a parameter a default value, so the caller may omit it. Named arguments, available in modern versions, let the caller state which value belongs to which parameter, which improves readability when a function has many options.
Return values and types
A function usually returns a value, and PHP allows you to declare the type that it returns. A function may also return nothing. Declaring parameter and return types is a strong habit, because mistakes appear early and the intention is documented in the function itself.
Built-in functions
PHP ships with a very large number of built-in functions for strings, arrays, dates, files and more. Before writing your own helper, check the official manual, because a ready-made function may already exist. Reading the manual is an essential skill, and the page for each function explains its parameters, return value and examples.
Anonymous functions
PHP supports functions without a name that can be stored in a variable or passed to another function. They are often used for small pieces of logic, for example when sorting a list by a custom rule or filtering items. A shorter arrow form exists for simple cases.
What are classes and objects?
A class is a blueprint. An object is a thing built from that blueprint. A class called Student could describe what every student has, such as a name and a roll number, and what every student can do, such as report a grade. Each individual student is an object created from the class, with its own values.
The data stored in an object is held in properties. The actions an object can perform are written as methods. A special method called the constructor runs when an object is created and prepares its initial state.
What do public, protected and private mean?
Encapsulation means keeping the internal details of an object hidden and exposing only what is necessary. PHP offers three visibility levels. Public members can be used from anywhere. Protected members can be used inside the class and its children. Private members can be used only inside the class itself. By keeping properties private and giving controlled access through methods, you can protect the object from being placed in an invalid state.
How does inheritance work?
Inheritance lets a class build on another class. The child class receives the properties and methods of the parent and can add or change behaviour. For instance, a general Vehicle class could be extended by Car and Bike classes. Inheritance is useful, but it can become tangled if used for everything. Many experienced developers prefer to combine objects, a practice often summarised as preferring composition over inheritance, when the relationship is not truly of the kind that one thing is a special type of another.
What are interfaces and abstract classes?
An interface is a contract. It lists the methods that a class must provide, without saying how they work. Different classes can follow the same contract in their own way. For example, several payment gateways could all promise a method to start a payment, so the rest of the application can use any of them in the same manner.
An abstract class is a partly finished class. It may contain common behaviour and also declare methods that child classes must complete. It cannot be created directly.
What are traits for?
PHP supports single inheritance, meaning a class has only one parent. Traits let you reuse a group of methods across unrelated classes without inheritance. They are useful for small pieces of shared behaviour, such as adding a time stamp feature, but should be used with restraint so that the code stays easy to follow.
Ways to share and structure behaviour
| Tool | What it does | Key point |
|---|---|---|
| Inheritance | A child class receives the public and protected members of its parent | One parent per class; private parent methods are not accessible to the child |
| Interface | Lists the methods a class must implement without saying how | A class can implement several interfaces; interface methods are public |
| Abstract class | A partly finished class with shared behaviour and methods children must complete | Cannot be created directly |
| Trait | A group of methods reused in unrelated classes | Cannot be instantiated on its own; used with the use keyword |
Static members and constants
Some data belongs to the class itself and not to each object. Static properties and methods are accessed through the class name. Class constants hold fixed values that relate to the class. Use static members sparingly, because they behave like global state and can make testing harder.
Why use namespaces and autoloading?
In larger projects, many classes may share the same name. Namespaces group classes under a prefix to avoid clashes, much like folders for files. Autoloading loads a class file automatically when the class is first needed, so you do not have to include each file by hand. The community standards for these conventions are published as PSR recommendations, and Composer, the dependency manager, follows them.
What are exceptions?
When something unexpected happens, a function can signal the problem by throwing an exception. The calling code can catch it and respond, for instance by showing a friendly message or by trying another action. Exceptions keep error handling separate from normal logic and avoid the habit of returning special values for failure.
Principles worth knowing
- Single responsibility: a class should have one reason to change.
- Dependency injection: pass the objects a class needs into it instead of creating them inside, which makes testing easier.
- Readable naming: names should reveal intent.
- Small interfaces: do not force a class to depend on methods it does not use.
You do not have to master every principle at once. Start by writing small functions, then group related data and behaviour into classes, and refactor as you learn.
Practice ideas
- Model a library with books and members as classes and describe how they relate.
- Create an interface for notifications and imagine email and SMS versions.
- Take a long procedural script and split it into functions with clear names.
Working through such exercises will make object oriented design feel natural and will prepare you for frameworks, which rely on these ideas heavily.
Sources and further reading
- PHP Manual: Visibility: defines public, protected and private for properties and methods.
- PHP Manual: Object inheritance: explains that a subclass inherits public and protected members and may override them.
- PHP Manual: Object interfaces: explains that an interface specifies the methods a class must implement without defining how, and that a class may implement several.
- PHP Manual: Traits: describes traits as a mechanism for code reuse in single inheritance languages that cannot be instantiated on their own.
- PHP Manual: Namespaces overview: gives the two purposes of namespaces: avoiding name collisions and aliasing long names.
Frequently asked questions
What is the difference between a class and an object?
A class is a blueprint, while an object is a particular instance built from that blueprint with its own values.
What are public, protected and private in PHP?
They are visibility levels: public is open to all code, protected is limited to the class and its children, and private is limited to the class itself.
What is an interface in PHP?
An interface is a contract that lists the methods a class must provide, without describing how they work.
Why use traits?
Traits let unrelated classes reuse a group of methods without inheritance, which helps share small pieces of behaviour.