33. Properties (Attributes) and Methods (Behaviors)
This lesson deepens the understanding of the two core components of a class.
Properties (Data)
Properties are variables defined within a class. In modern PHP, they must be declared with an access modifier (like public, covered in Lesson 35).
php
<?php class User { public $username; public $email; private $password_hash; // More secure, covered later } ?>Methods (Behavior)
Methods are functions defined within a class that operate on the object's data or perform actions.
Accessing Properties inside Methods:
Methods use the $this keyword followed by the arrow (->) operator to access the object's properties.
php
<?php class Calculator { public function add($a, $b) { return $a + $b; } public function describeOperation() { // $this->a or $this->b would not work here if they aren't properties. return "This method performs addition."; } } $calc = new Calculator(); echo $calc->add(10, 5); ?>Property Default Values
Properties can be initialized with default values during their declaration.
php
<?php class Product { public $status = 'In Stock'; public $price; public function getStatus() { return $this->status; } } $p = new Product(); echo $p->getStatus(); // Output: In Stock ?>