w1coding.comAll tutorials

PHP Class

PHP lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Basics
  5. Operators
  6. Control
  7. Loops
  8. Variables
  9. Functions
  10. Arrays
  11. Superglobal
  12. File
  13. Loops
  14. Date
  15. Loops
  16. Strings
  17. Error
  18. Class
  19. File
  20. Include
  21. Sessions
  22. Mysql
  23. Cookies
  24. Forms
  25. Cookies
  26. Regular
  27. Authenthication
  28. Fileupload
  29. Mvc
  30. Responsive

PHP Classes and Objects

In object-oriented programming (OOP) in PHP, classes and objects are the building blocks. A class defines a blueprint, and an object is an instance of that class.

Creating a Class

To create a class in PHP, use the class keyword:

      
        <?php
          class Car {
            public $color;
            public $model;

            public function __construct($color, $model) {
              $this->color = $color;
              $this->model = $model;
            }

            public function getDetails() {
              return "This car is a $this->color $this->model.";
            }
          }

          $myCar = new Car("Red", "Toyota");
          echo $myCar->getDetails(); // Outputs: This car is a Red Toyota.
        ?>
      
    

Activity

Try It Yourself!

Write a class for a Person that stores their name and age. Create an object of the class and display the person's name and age.

Quiz

Quick Quiz

  1. What is the difference between a class and an object in PHP?
  2. How do you create a constructor in a PHP class?

Answers: A class defines a blueprint, and an object is an instance of the class. You create a constructor with the __construct() method.