PHP - Accessing Object Properties from Methods

Introduction

You should make method as self-contained as possible.

An object's methods should ideally work mainly with the properties of the object, rather than relying on outside data to do their job.

To access an object's property from within a method of the same object, you use the special variable name $this, as follows:

$this->property;

For example:

Demo

<?php
class MyClass {/*from  ww  w.j  a  v a 2s .  c om*/

          public $greeting ="Hello, World!";

          public function hello() {
            echo $this->greeting;
          }
}
$obj = new MyClass;
$obj->hello();  // Displays"Hello, World!"
?>

Result

Here, a class, MyClass, is created, with a single property, $greeting, and a method, hello().

The method uses echo to display the value of the $greeting property accessed via $this->greeting.

After the class definition, the script creates an object, $obj, from the class, and calls the object's hello() method to display the greeting.

The $this inside the hello() method refers to the specific object whose hello() method is being called - in this case, the object stored in $obj.

If another object, $obj2, were to be created from the same class and its hello() method called, the $this would then refer to $obj2 instead, and therefore $this->greeting would refer to the $greeting property of $obj2.

You can use $this to call an object's method from within another method of the same object:

Demo

<?php
         class MyClass {

          public function getGreeting() {
            return"Hello, World!";
          }// w  w w  .  j a va  2  s .  c  o m

          public function hello() {
            echo $this->getGreeting();
          }
         }

         $obj = new MyClass;
         $obj->hello();  // Displays"Hello, World!"
?>

Result

Here, the hello() method uses $this->getGreeting() to call the getGreeting() method in the same object, then displays the returned greeting string using echo.

Related Topic