Using the keyword “this” in PHP

You may have come across number of functions and variables inside a class and perhaps you don’t even know how they’re called or invoked. These functions and variables that belong to a class are called as properties and methods, or simply members, of this class.

In PHP, the keyword “$this” is used as a self reference of a class and you can use it for calling and using these properties and methods as shown in the example bellow.

Create a file ClassOne.php with code bellow:
<?php

class ClassOne
{
    // this is a property of this class
    public $propertyOne;

    // When the ClassOne is instantiated, the first method called is
    // its constructor, which also is a method of the class
    public function __construct($argumentOne)
    {
        // this key word used here to assign
        // the argument to the class
        $this->propertyOne = $argumentOne;
    }

    // this is a method of the class
    function methodOne()
    {
        //this keyword also used here to use  the value of variable $var1
        return 'Method one print value for its '
             . ' property $propertyOne: ' . $this->propertyOne;
    }
}

In this class, we are also using the visibility declarations (public), which means whether the members are accessible on a subclass – we will discuss it later – or instance.
Another thing you must be curious about is the use of ‘->’. This is an object pointer and, on PHP, it’s used for accessing members inside an object.

Now, let’s test your class! Create another file, called use.php with the following code:
<?php

// include your class file
require_once 'ClassOne.php';

// Create an instance of your class
$classOneInstance = new ClassOne('Hello');

// And test it
print $classOneInstance->propertyOne . '<br />';
print $classOneInstance->methodOne();

- Note that in both files we’re not using the enclosing PHP tags (?>). Once they have only PHP code, it’s not needed and it’s also a good practice to avoid them on pure PHP files.

1 user responded to this post

mygif designsoft said in July 9th, 2009 at 5:09 pm

This keyword play an role in php like java.This is an important feature of object oriented programming.Visit to learn more affordable website design

You must be logged in to post a comment.

full indir download