DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Inheritance in PHP: A Simple Guide With Examples
  • The Blue Elephant in the Room: Why PHP Should Not Be Ignored Now or Ever
  • Laravel for Beginners: An Overview of the PHP Framework
  • Is PHP Still the Best Language in 2024?

Trending

  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • The Modern Data Stack Is Overrated — Here’s What Works
  • Accelerating AI Inference With TensorRT
  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  1. DZone
  2. Coding
  3. Languages
  4. Learn PHP - How to Write A Class in PHP

Learn PHP - How to Write A Class in PHP

By 
Ajitesh Kumar user avatar
Ajitesh Kumar
·
Oct. 09, 14 · Interview
Likes (1)
Comment
Save
Tweet
Share
118.3K Views

Join the DZone community and get the full member experience.

Join For Free

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.

That is it!

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 <?php and ?>

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
  • -&gt; used to invoke methods on the object

<?php
require "User.php";
 
$h = new User( "Calvin", 15 );
echo "Hello, " . $h->getName(). "! You are ". $h->isAdult();
?>
<br/>
<?php
$h = new User( "Chris", 39 );
echo "Hello, " . $h->getName(). "! You are ". $h->isAdult();
?>


PHP

Published at DZone with permission of Ajitesh Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Inheritance in PHP: A Simple Guide With Examples
  • The Blue Elephant in the Room: Why PHP Should Not Be Ignored Now or Ever
  • Laravel for Beginners: An Overview of the PHP Framework
  • Is PHP Still the Best Language in 2024?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!