- How to Use PHP Classes Correctly with Code Examples in 2023
- What is a Class in PHP
- Class and Object – PHP OOP Basics
- Properties
- Behaviors
- Creating Classes in PHP Code Example
- Class in PHP
- Properties of a Class in PHP
- Static vs Non Static
- Access Modifiers
- Constructor of a Class in PHP
- Getter and Setter functions
- Non-static methods
- Static methods
- Objects of a class in PHP
- Conclusion
- Want to learn more about PHP?
- Learn the Fundamentals of Good Web Development
- Learn PHP — How to Write A Class in PHP
- Why Write a PHP Class?
- Key Aspects of a PHP Class
- A PHP Class – Code Example
- Using PHP Class in PHP files
How to Use PHP Classes Correctly with Code Examples in 2023
PHP classes are a subset of objects. They can an entire object model. They have properties and functions. They are a core feature of object-oriented programming in PHP. Check out the article to read more.
What is a Class in PHP
. A class is a fundamental concept in object oriented programming so the article features a section about PHP OOP basics. If you’re already familiar with OOP concepts you can jump straight to the example following the OOP basics section.
However, we recommend staying tuned from beginning to end to gain some really good insights about PHP OOP and especially about the concept of a class in PHP.
Class and Object – PHP OOP Basics
A class is a fundamental concept in object-oriented programming. It is a blueprint or a template that defines an entity. The cool thing about a class is that you can create objects based on it. Let’s understand this class and object concept with an analogy.
Properties
A master plan (class) forms a baseline for producing various cars in the image above. These cars have a color property that differs. A class defines properties, and objects assign values to these properties during construction.
Behaviors
But properties are one aspect of a class. A class also defines behaviour which in this analogy will be functions and behaviours relevant to cars, for instance, accelerating, decelerating, or breaking.
All the objects of the same class exhibit similar behaviour. So, all these cars may look different, but they all exhibit the same behaviours or functions.
Creating Classes in PHP Code Example
As we have learned about classes and objects, let’s understand how they occur in code. Here’s a complete version of the Car class. Don’t worry about all the new keywords, as we will be building this class from the ground up in the following sections.
color = $color; $this->set_chasis($chassis); > function get_chasis() < return $this->chassis; > function set_chasis($chassis) < $this->chassis = $chassis; > function accelerate() < echo 'Accelerating'; >function decelerate() < echo 'Decelerating'; >static function welcome() < echo 'Welcome from '.self::$make; >> ?>
Seems horribly difficult! Let’s not worry and learn it from the ground up.
Class in PHP
Defining a class is easy. Just type the keyword class followed by the class name, for instance – Car. By conventions, a class name should be capitalized. Moreover, keywords are case-sensitive so try not to type Class instead of class.
Voila! We have the class in place. Let’s start defining properties next.
Properties of a Class in PHP
Let’s define a few properties of the Car class.
So, we have three properties in there – color, chassis and make.
Note that the make has already been set to “Serpent”. There are some new keywords right there so let’s quickly see them.
Static vs Non Static
The keyword static defines a class level property or a method. So the static members bind directly to class and you don’t need an object to access or modify them. For instance, the Car class here defines a make “Serpent”.
Now all the objects – cars are still “Serpent” regardless of the difference in their color or chassis. Contrary to static, the non-static members are bound to the object only, for instance, the color property is set when the car object is built and thus every car has different color.
Access Modifiers
You would be wondering about the keywords like public and private. These are access modifiers. Let’s see what are access modifiers.
Access modifiers controls the visibility of a property or a method. Sometimes you want to keep information strictly private and other times publicly available. Access modifiers thus controls the access to properties and methods.
The three access modifiers are:
- public – The property or method can be accessed from anywhere. (Default)
- protected – The property or method can be accessed withn the class and its subclasses.
- private – The property or method can be accessed within the class only.
Private is the most strict modifier and thus doesn’t allow accessing or modifying the properties or methods directly. The class thus provide getter and setter functions to access and initiate the private members.
Constructor of a Class in PHP
The constructor function is invoked as we instantiate or in other words create objects. The constructor function initiates the properties of objects right at the time of constructing them. Let’s add a constructor function.
color = $color; $this->set_chasis($chassis); > > ?>
The constructor function helps assign values to color and chassis, through the setter function.
Getter and Setter functions
As we have already discussed that private properties are not accessible outside the class. However, the getter and setter function allows us to access or set these properties indirectly. Well, this is data encapsulation which is yet another famous concept in OOP.
Let’s add getters and setters to the class.
color = $color; $this->set_chasis($chassis); > function get_chasis() < return $this->chassis; > function set_chasis($chassis) < $this->chassis = $chassis; > > ?>
We will interact with the chassis through these methods rather than trying to access them directly.
Non-static methods
Non-static methods are bound to the objects of a class. They are only invoked on an object and couldn’t be invoked by a class directly. Let’s add some non-static methods.
color = $color; $this->set_chasis($chassis); > function get_chasis() < return $this->chassis; > function set_chasis($chassis) < $this->chassis = $chassis; > function accelerate() < echo 'Accelerating'; >function decelerate() < echo 'Decelerating'; >> ?>
Perfect! All the car objects would be able to accelerate and decelerate.
Static methods
Static members are class level properties and methods. You don’t need to instantiate objects for accessing them. Let’s add a generic welcome function to the class.
color = $color; $this->set_chasis($chassis); > function get_chasis() < return $this->chassis; > function set_chasis($chassis) < $this->chassis = $chassis; > function accelerate() < echo 'Accelerating'; >function decelerate() < echo 'Decelerating'; >static function welcome() < echo 'Welcome from '.self::$make; >> ?>
Voila! The class is now completely built. Let’s instantiate a few objects of the Car.
Objects of a class in PHP
The following code instantiates two objects of the class Car and invokes the accelerate method. Also, note that the color property is public and could be accessed directly while the private property chassis is accessed through a getter method.
Car::welcome(); //Static method. $car1 = new Car('Red', '111-010-220'); $car2 = new Car('Green', '007-010-210'); echo $car1->color.' car is '.$car1->accelerate(); echo $car2->color.' car is '.$car2->accelerate(); /* Welcome from Serpent Red car with chassis 111-010-220 is Accelerating Green car with chassis 007-010-210 is Accelerating */
We have the cars running now so let’s race to the conclusion now.
Conclusion
That’s all for this article. We have covered alot of ground here starting from PHP OOP basics to writing a Car class and instantiating its objects. The article includes explanations of some important concepts like static and non-static as well as access modifiers.
These are pretty much the basics. If you want to learn more about PHP OOP and PHP in general, stay tuned at FuelingPHP.
Want to learn more about PHP?
We have many fun articles related to PHP. You can explore these to learn more about PHP.
Learn the Fundamentals of Good Web Development
Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.
Learn PHP — How to Write A Class in PHP
Join the DZone community and get the full member experience.
This article represents some high-level concepts and a code example on how to write a PHP class and use it elsewhere. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.
Following are some of the key points described later in this article:
- Why write a PHP class?
- Key aspects of a PHP class
- A PHP class – Code Example
- Using PHP class in PHP files
Why Write a PHP Class?
As a beginner, I have come across this common thing that PHP developers tend to write one or more functions in the PHP files/scripts. As a matter of fact, I have also come across several projects (profitable ones) which were written with a few PHP files, very large ones, having all the code put in them in form of multiple functions. When learning PHP, it is OK to do in this way. However, for web apps to go to production, this may not be the recommended way. Following are some of the disadvantages of writing PHP scripts with just the functions in it:
- Low Maintainability: These files with functions are difficult to maintain/manage (change). Thinking of writing unit tests is like next to impossible. In addition to low testability, there may be several functions which could be reused. However, due to the way they get written, the files score low on re-usability as well. It also propagates the code duplication which further impacts code maintainability as changing a functionality would require change at several places.
- Low Usability: These files are difficult to read and understand.
To take care of some of the above issues, one should learn writing PHP using object-oriented manner, e.g., writing code in form of one or more classes. Writing PHP code using classes helps one should segregate similar looking functions in a class (Single Responsibility Principle) and use the class elsewhere in the code (different PHP scripts). As a matter of fact, one could easily follow SOLID principle with PHP and make the code well-structured. Doing this way does propagate high maintainability (high testability, high cohesiveness, high reusability etc) and makes code readable and understandable.
Key Aspects of a PHP Class
Following are some of the key aspects of a PHP class:
- Define a class with keyword “class” followed by name of the class
- Define the constructor method using “__construct” followed by arguments. The object of the class can then be instantiated using “new ClassName( arguments_list )”
- Define class variables. One could access specifiers such as private, public, protected etc.
- Define methods using “function” keyword. By default, PHP methods, if not specified with any access specifier becomes public in nature.
A PHP Class – Code Example
Following is the code example of a PHP class, User. Pay attention to some of the following:
- “class” followed by “User”, the class name
- Member variables such as $name, $age
- Member functions such as getName, isAdult
class User < private $name; private $age; function __construct( $name, $age ) < $this->name = $name; $this->age = $age; > function getName() < return $this->name; > function isAdult() < return $this->age >= 18?"an Adult":"Not an Adult"; > >
Save the file as User.php. Don’t forget to put the above code within
Using PHP Class in PHP files
Finally, its time to use the PHP class. If you are working with a sample project, go to index.php. Assuming that User.php is saved in same folder as index.php, following is how the code would look like. Pay attention to some of the following:
- “require” keyword used to include User class written inside User.php
- “new” keyword used to instantiate the User class
- -> used to invoke methods on the object
getName(). "! You are ". $h->isAdult(); ?>
getName(). "! You are ". $h->isAdult(); ?>
Published at DZone with permission of Ajitesh Kumar , DZone MVB . See the original article here.
Opinions expressed by DZone contributors are their own.