Current Location: Home> Latest Articles> PHP Object-Oriented Programming: A Detailed Explanation of 3 Data Access Methods with Code Examples

PHP Object-Oriented Programming: A Detailed Explanation of 3 Data Access Methods with Code Examples

gitbox 2025-06-24

1. Introduction

PHP, as a widely used backend programming language, is known for its script-based nature, which allows for fast execution. This is one of the key reasons PHP is so popular for web development. Object-Oriented Programming (OOP) in PHP provides developers with better code structure, making it more readable and reusable.

2. Three Data Access Methods

In PHP object-oriented programming, data access methods are a key part of class design. PHP supports three primary ways to access data:

2.1. Public Properties

Public properties can be accessed both inside and outside the class, typically using the arrow operator (->) for access.

class Car {
   public $color;
   public function __construct($color) {
      $this->color = $color;
   }
}

$car1 = new Car("blue");
echo $car1->color;

2.2. Protected Properties

Protected properties can only be accessed within the current class and its subclasses. They cannot be accessed outside the class, and the arrow operator (->) is also used for access.

class Car {
   protected $color;
   public function __construct($color) {
      $this->color = $color;
   }
}

class SportCar extends Car {
   public function showColor() {
      echo $this->color;
   }
}

$car1 = new SportCar("red");
$car1->showColor();

2.3. Private Properties

Private properties can only be accessed within the current class and not outside. Again, the arrow operator (->) is used for access.

class Car {
   private $weight;
   public function __construct($weight) {
      $this->weight = $weight;
   }

   public function showWeight() {
      echo $this->weight;
   }
}

$car1 = new Car("2000");
$car1->showWeight();

3. Conclusion

This article has introduced the three common data access methods in PHP object-oriented programming: public properties, protected properties, and private properties. Understanding and mastering these fundamental concepts will significantly improve code readability, maintainability, and reusability, which are crucial for writing high-quality code.