PHP Class (Object-Oriented Programming) Creation Tutorial

In this tutorial, you will learn how to How Create a PHP Class and its usage. The tutorial aims to provide IT/CS students and beginners with a reference for learning how to write a PHP script using Object-Oriented Programming (OPP) approach. Here, sample snippets are provided to have a better understanding. A sample source code zip file is also provided and is free to download.

What is PHP Class?

PHP Class is an object template whereas an object is a class instance. Classes contain properties and methods that are reusable. It can also be used for many more purposes such as defining entities of known properties and behaviors, group-related behaviors or states, messages to functions or other objects, and describing hierarchies and inheritance within an application.

Snippets

Here are the sample snippets for creating and using the PHP Class.

  1. <?php
  2.  
  3. class DatabaseConnection {
  4. protected $host;
  5. protected $username;
  6. protected $password;
  7. protected $dbname;
  8. public $conn;
  9.  
  10. public function __constructor($host, $username, $password, $dbname){
  11. $this->host = $host;
  12. $this->host = $username;
  13. $this->host = $password;
  14. $this->host = $dbname;
  15.  
  16. $this->connect();
  17. }
  18. public function connect(){
  19. $this->conn= new mysqli($this->host, $this->username, $this->password, $dbname);
  20. if(!$this->conn)
  21. throw new ErrorException($this->conn->error, $this->conn->errno);
  22. }
  23.  
  24. public function __destruct(){
  25. $this->conn->close();
  26. }
  27. }
  28. $db = new DatabaseConnection("localhost", "root", "", "my_site_db");
  29. ?>

The snippet above demonstrates the creation of a simple PHP Class for the database connection of a web application. The class provided is composed of both public and protected properties or variables whereas the public variables can be accessed outside the class and the other class is derived from the current class while the private variables can be accessed only within the actual class. The __constructor() is the constructor that initializes the object wherein the sample provided, the database credentials are being passed, and triggers the database connection method upon the creation of the object. The __destructor() method will be executed when the objects or scripts are stopped or exited whereas, on the sample snippet, the database connection will be automatically closed after the DatabaseConnection object has been destructed.

In the given snippet, we can simply use the object property for making queries using the MySQLi driver. Check out the sample MySQL query below for the usage of created DatabaseConnection Object.

  1. <?php
  2. $query = $db->conn->query("SELECT * FROM `posts`");
  3. ?>

Example

Here's another example of using PHP Class. Let's assume that the script below is saved and named MySampleClass.php.

  1. <?php
  2. class MySampleClass {
  3. /**
  4.   * Predefined variables
  5.   */
  6. protected $protectedVar = "Protected Only";
  7. public $publicVar = "Sample Public Variable Value";
  8. private $privateVar = "Sample Private Variable Value. Other Classes cannot access this.";
  9.  
  10. public function __construct(){
  11. /**
  12.   * construct the sample class object
  13.   */
  14. $this->publicVar = 'Public Variable has been updated in class constructor.';
  15. }
  16. /**
  17.   * Public Function/Method
  18.   */
  19. public function samplePublicMethod(){
  20. return "This is a sample Public Method/Function of a class return value.";
  21. }
  22. /**
  23.   * Protected Function/Method
  24.   */
  25. protected function sampleProtectedMethod(){
  26. return "This is a sample Protected Method/Function of a class return value.";
  27. }
  28.  
  29. public function executeInsideClass(){
  30. ?>
  31. <dl>
  32. <dt class="fw-light">Object Return Value:</dt>
  33. <dd class="ps-4"><pre><?php print_r($this); ?></pre></dd>
  34. </dl>
  35. <dl>
  36. <dt class="fw-light">Public Predefined Variable Value:</dt>
  37. <dd class="ps-4"><pre><?php print_r($this->publicVar); ?></pre></dd>
  38. </dl>
  39. <dl>
  40. <dt class="fw-light">Protected Predefined Variable Value:</dt>
  41. <dd class="ps-4"><pre><?php print_r($this->protectedVar ?? "Can't Access this Class method."); ?></pre></dd>
  42. </dl>
  43. <dl>
  44. <dt class="fw-light">Private Predefined Variable Value:</dt>
  45. <dd class="ps-4"><pre><?php print_r($this->privateVar ?? "Can't Access this Class method."); ?></pre></dd>
  46. </dl>
  47. <dl>
  48. <dt class="fw-light">Public Class Method Return Value:</dt>
  49. <dd class="ps-4"><pre><?php print_r($this->samplePublicMethod()); ?></pre></dd>
  50. </dl>
  51. <dl>
  52. <dt class="fw-light">Protected Class Method Return Value:</dt>
  53. <dd class="ps-4"><pre><?php print_r((is_callable([$this, 'sampleProtectedMethod'])) ?$this->sampleProtectedMethod() : "Permission Denied! Can't Access 'sampleProtectedMethod()' method."); ?></pre></dd>
  54. </dl>
  55. <?php
  56. return ob_get_clean();
  57. }
  58. public function __destruct(){
  59. /**
  60.   * destruct the sample class object
  61.   */
  62. }
  63. }
  64.  
  65. $sampleClass = new MySampleClass();
  66. require_once('extendedClass.php');
  67. $extendedClass = new extendedClass();

And the script below is named extendedClass.php.

  1. <?php
  2. /**
  3.   * A sample PHP class that extends the other Class
  4.   */
  5. class extendedClass extends MySampleClass {
  6. public function getPropertyMethods(){
  7. ?>
  8. <dl>
  9. <dt class="fw-light">Object Return Value:</dt>
  10. <dd class="ps-4"><pre><?php print_r($this); ?></pre></dd>
  11. </dl>
  12. <dl>
  13. <dt class="fw-light">Public Predefined Variable Value:</dt>
  14. <dd class="ps-4"><pre><?php print_r($this->publicVar); ?></pre></dd>
  15. </dl>
  16. <dl>
  17. <dt class="fw-light">Protected Predefined Variable Value:</dt>
  18. <dd class="ps-4"><pre><?php print_r($this->protectedVar ?? "Can't Access this Class method."); ?></pre></dd>
  19. </dl>
  20. <dl>
  21. <dt class="fw-light">Private Predefined Variable Value:</dt>
  22. <dd class="ps-4"><pre><?php print_r($this->privateVar ?? "Can't Access this Class method."); ?></pre></dd>
  23. </dl>
  24. <dl>
  25. <dt class="fw-light">Public Class Method Return Value:</dt>
  26. <dd class="ps-4"><pre><?php print_r($this->samplePublicMethod()); ?></pre></dd>
  27. </dl>
  28. <dl>
  29. <dt class="fw-light">Protected Class Method Return Value:</dt>
  30. <dd class="ps-4"><pre><?php print_r((is_callable([$this, 'sampleProtectedMethod'])) ?$this->sampleProtectedMethod() : "Permission Denied! Can't Access 'sampleProtectedMethod()' method."); ?></pre></dd>
  31. </dl>
  32. <?php
  33. return ob_get_clean();
  34. }
  35. }

Then the page interface will be the script below named index.php.

  1. <?php require_once('MySampleClass.php') ?>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>PHP OOP - Classes and Objects</title>
  8. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  9. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  10. <link rel="stylesheet" href="assets/css/styles.css">
  11. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  12. <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
  13. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  14.  
  15. <script src="assets/js/script.js"></script>
  16.  
  17. </style>
  18. </head>
  19. <main>
  20. <nav class="navbar navbar-expand-lg navbar-dark bg-gradient">
  21. <div class="container">
  22. <a class="navbar-brand" href="./">PHP OOP - Classes and Objects</a>
  23.  
  24. <div>
  25. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  26. </div>
  27. </div>
  28. </nav>
  29. <div id="main-wrapper">
  30. <div class="container-fluid px-5 my-3" >
  31. start_loader()
  32. </script>
  33. <div class="row">
  34. <div class="mx-auto col-lg-6 col-md-6 col-sm-12 col-xs-12">
  35. <div class="card rounded-0 mb-3 shadow">
  36. <div class="card-header rounded-0">
  37. <div class="card-title"><b>Calling the Class Property or Methods Outside the Class</b></div>
  38. </div>
  39. <div class="card-body rounded-0">
  40. <div class="container-fluid">
  41. <!-- PHP Class Method Execution -->
  42. <div>
  43. <dl>
  44. <dt class="fw-light">Object Return Value:</dt>
  45. <dd class="ps-4"><pre><?php print_r($sampleClass); ?></pre></dd>
  46. </dl>
  47. <dl>
  48. <dt class="fw-light">Public Predefined Variable Value:</dt>
  49. <dd class="ps-4"><pre><?php print_r($sampleClass->publicVar); ?></pre></dd>
  50. </dl>
  51. <dl>
  52. <dt class="fw-light">Protected Predefined Variable Value:</dt>
  53. <dd class="ps-4"><pre><?php print_r($sampleClass->protectedVar ?? "Can't Access this Class method."); ?></pre></dd>
  54. </dl>
  55. <dl>
  56. <dt class="fw-light">Private Predefined Variable Value:</dt>
  57. <dd class="ps-4"><pre><?php print_r($sampleClass->privateVar ?? "Can't Access this Class method."); ?></pre></dd>
  58. </dl>
  59. <dl>
  60. <dt class="fw-light">Public Class Method Return Value:</dt>
  61. <dd class="ps-4"><pre><?php print_r($sampleClass->samplePublicMethod()); ?></pre></dd>
  62. </dl>
  63. <dl>
  64. <dt class="fw-light">Protected Class Method Return Value:</dt>
  65. <dd class="ps-4"><pre><?php print_r((is_callable([$sampleClass, 'sampleProtectedMethod'])) ?$sampleClass->sampleProtectedMethod() : "Permission Denied! Can't Access 'sampleProtectedMethod()' method."); ?></pre></dd>
  66. </dl>
  67. </div>
  68. <!-- End of PHP Try Catch Error Handling Snippet -->
  69. </div>
  70. </div>
  71. </div>
  72. </div>
  73. <div class="mx-auto col-lg-6 col-md-6 col-sm-12 col-xs-12">
  74. <div class="card rounded-0 mb-3 shadow">
  75. <div class="card-header rounded-0">
  76. <div class="card-title"><b>Calling the Class Property or Methods Inside the Class</b></div>
  77. </div>
  78. <div class="card-body rounded-0">
  79. <div class="container-fluid">
  80. <!-- PHP Class Method Execution -->
  81. <div>
  82. <?= $sampleClass->executeInsideClass() ?>
  83. </div>
  84. <!-- End of PHP Try Catch Error Handling Snippet -->
  85. </div>
  86. </div>
  87. </div>
  88. </div>
  89. <div class="mx-auto col-lg-6 col-md-6 col-sm-12 col-xs-12">
  90. <div class="card rounded-0 mb-3 shadow">
  91. <div class="card-header rounded-0">
  92. <div class="card-title"><b>Calling the Class Property or Methods Inside the Extended Class</b></div>
  93. </div>
  94. <div class="card-body rounded-0">
  95. <div class="container-fluid">
  96. <!-- PHP Class Method Execution -->
  97. <div>
  98. <?= $extendedClass->getPropertyMethods() ?>
  99. </div>
  100. <!-- End of PHP Try Catch Error Handling Snippet -->
  101. </div>
  102. </div>
  103. </div>
  104. </div>
  105. </div>
  106. </div>
  107. </div>
  108. <footer class="bg-gradient shadow-top py-4 col-auto">
  109. <div class="">
  110. <div class="text-center text-light">
  111. All Rights Reserved &copy; <span id="dt-year"></span> | <span class="text-light text-opacity-75">PHP OOP - Classes and Objects</span>
  112. </div>
  113. <div class="text-center">
  114. <a href="mailto:[email protected]" class="text-decoration-none text-white">[email protected]</a>
  115. </div>
  116. </div>
  117. </footer>
  118. </main>
  119.  
  120. </body>
  121. </html>

The MySampleClass object is the main class that is included on the application page and the extendedClass is an object that derives from MySampleClass. The main class is composed of multiple public, private, and protected properties and methods. The public methods and properties are callable on the page interface script. The protected properties and methods are callable in both objects or classes. The Private property is only callable to the class itself.

Snapshots

Here are the snapshots of the output of the sample PHP program that I provided above.

Calling the Properties and Methods return values outside the classes

PHP Class OOP

Calling the Properties and Methods return values inside the main class

PHP Class OOP

Calling the Properties and Methods return values inside the class that extends the main class

PHP Class OOP

I have also provided the source code zip file that I created for this tutorial on this site and is free to download. You can download it by clicking the download button below this tutorial's content.

That's the end of this tutorial. I hope this PHP Class Object-Oriented Programming (OOP) Creation Tutorial will help you to understand more about PHP Classes and Objects. Also, I hope that you'll find this useful for future and current PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =D

Add new comment