Back to course

Properties (Attributes) and Methods (Behaviors)

PHP: The Complete 0 to Hero Bootcamp

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

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

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

status; } } $p = new Product(); echo $p->getStatus(); // Output: In Stock ?>