0
0
PHPprogramming~5 mins

Methods and $this keyword in PHP

Choose your learning style9 modes available
Introduction

Methods let you group actions inside a class. The $this keyword helps you access the current object's properties and methods.

When you want to organize code that belongs to an object.
When you need to change or read data inside an object.
When you want to reuse code inside the same object.
When you want to keep data and actions together for clarity.
When you want to create multiple objects with similar behavior.
Syntax
PHP
<?php
class ClassName {
    public $property;

    public function methodName() {
        // Use $this->property or $this->methodName()
    }
}
?>

Methods are functions inside a class.

$this refers to the current object instance.

Examples
This method uses $this->name to get the dog's name.
PHP
<?php
class Dog {
    public $name;

    public function bark() {
        echo $this->name . " says Woof!";
    }
}
?>
Methods change and return the object's property using $this.
PHP
<?php
class Counter {
    public $count = 0;

    public function increment() {
        $this->count++;
    }

    public function getCount() {
        return $this->count;
    }
}
?>
Sample Program

This program creates a Car object with a color. The describe method uses $this->color to print the color.

PHP
<?php
class Car {
    public $color;

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

    public function describe() {
        echo "This car is " . $this->color . ".\n";
    }
}

$myCar = new Car("red");
$myCar->describe();
?>
OutputSuccess
Important Notes

Always use $this inside methods to access properties or other methods of the same object.

You cannot use $this outside of class methods.

Remember to use -> to access properties or methods with $this.

Summary

Methods are functions inside classes that define object behavior.

$this refers to the current object and lets you access its data and actions.

Use methods and $this to keep code organized and connected to the object.