Using this in php classes

PHP $this

Summary: in this tutorial, you will learn about PHP $this keyword and how to use $this inside a class to reference the current object.

What is $this in PHP?

In PHP, $this keyword references the current object of the class. The $this keyword allows you to access the properties and methods of the current object within the class using the object operator ( -> ):

$this->property $this->method()Code language: PHP (php)

The $this keyword is only available within a class. It doesn’t exist outside of the class. If you attempt to use the $this outside of a class, you’ll get an error.

When you access an object property using the $this keyword, you use the $ with the this keyword only. And you don’t use the $ with the property name. For example:

$this->balanceCode language: PHP (php)

The following shows the BankAccount class:

 class BankAccount < public $accountNumber; public $balance; public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > > public function withdraw($amount) < if ($amount $this->balance) < $this->balance -= $amount; return true; > return false; > >Code language: PHP (php)

In this example, we access the balance property via the $this keyword inside the deposit() and withdraw() methods.

Chaining methods

First, create a new BankAccount object:

// create a new account object $account = new BankAccount(); $account->accountNumber = 1; $account->balance = 100;Code language: PHP (php)

Second, call the deposit() method three times to deposit different amounts of money:

$account->deposit(100); $account->deposit(200); $account->deposit(300);Code language: PHP (php)

This code is quite verbose. It would be more concise and expressive if you can write these statements using a single statement like this:

$account->deposit(100) ->deposit(200) ->deposit(300);Code language: PHP (php)

This technique is called method chaining.

To form the chain, the deposit() method needs to return a BankAccount object, which is the $this inside the BankAccount class like this:

 class BankAccount < public $accountNumber; public $balance; public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > return $this; > public function withdraw($amount) < if ($amount $this->balance) < $this->balance -= $amount; return true; > return false; > >Code language: PHP (php)

The deposit() returns the $this which is the current object of the BankAccount class. Therefore, you can call any public method of the BankAccount class.

Читайте также:  PHP Program to show current page URL

The following example calls the deposit() method first and then the withdraw() method in a single statement:

$account->deposit(100) ->withdraw(150);Code language: PHP (php)

It’s equivalent to the following:

$account->deposit(100); $account->withdraw(150);Code language: PHP (php)

Summary

  • PHP $this keyword references the current object of the class. It’s only available within the class.
  • Do use the method chaining by returning $this from a method to make the code more concise.

Источник

PHP $this Keyword

If you are following this tutorial from the beginning or you started from the OOPS concepts, you must have noticed the usage of $this in some of the code snippets.

this keyword is used inside a class, generally withing the member functions to access non-static members of a class(variables or functions) for the current object.

Let’s take an example to understand the usage of $this .

name = $name; > // public function to get value of name (getter method) public function getName() < return $this->name; > > // creating class object $john = new Person(); // calling the public function to set fname $john->setName("John Wick"); // getting the value of the name variable echo "My name is " . $john->getName(); ?>

In the program above, we have created a private variable in the class with name $name and we have two public methods setName() and getName() to assign a new value to $name variable and to get its value respectively.

Whenever we want to call any variable of class from inside a member function, we use $this to point to the current object which holds the variable.

We can also use $this to call one member function of a class inside another member function.

Читайте также:  Mr. Camel

NOTE: If there is any static member function or variable in the class, we cannot refer it using the $this .

Using self for static Class Members

Instead of $this , for static class members(variables or functions), we use self , along with scope resolution operator :: . Let’s take an example,

Difference between PHP self and this

Let’s understand a few differences between self and this :

self this
self keyword is not preceded by any symbol. this keyword should be preceded with a $ symbol.
To access class variables and methods using the self keyword, we use the scope resolution operator :: In case of this operator, we use the —< symbol.
It is used to refer the static members of the class. It is used to access non-static members of the class.
PHP self refers to the class members, but not for any particular object. This is because the static members(variables or functions) are class members shared by all the objecxts of the class. Whereas, $this wil refer the member variables and function for a particular instance.

Let’s take a code example to understand this better:

name; > // public function to get job description public function getDesc() < return $this->desc; > // static function to get the company name public static function getCompany() < return self::$company; >// non-static function to get the company name public function getCompany_nonStatic() < return self::getCompany(); >> $objJob = new Job(); // setting values to non-static variables $objJob->name = "Data Scientist"; $objJob->desc = "You must know Data Science"; /* setting value for static variable. done using the class name */ Job::$company = "Studytonight"; // calling the methods echo "Job Name: " .$objJob->getName()."
"; echo "Job Description: " .$objJob->getDesc()."
"; echo "Company Name: " .Job::getCompany_nonStatic(); ?>

Job Name: Data Scientist Job Description: You must know Data Science Company Name: Studytonight

In the code snippet above we have a few non-static variables and one static variable.

Because the static members are associated with class itself and not the objects of the class, hence we call them using the class name.

Also, a static member function can use a static variable inside it, while if a non-static method use a static variable inside it, then it is also called using the class name, just like a static method.

Читайте также:  Display Webcam Stream

Источник

PHP $this class

To access or change a class method or property within the class itself, it’s necessary to prefix the corresponding method or property name with «$this» which refers to this class.

Access current class properties inside current class method

first + $this->second; echo "addition=".$add."
"; > function sub( ) < $sub=$this->first - $this->second; echo "subtraction=".$sub; > > $obj= new demo(); $obj->add(); $obj->sub(); ?>

In the above example Create a class demo with two global properties $first hold 1000 and $second hold 500. Now want to access these class properties inside class method add( ) and sub( ). So inside add( ) method call these class properties( to prefix the corresponding property name with “$this”) with the help of «$this», store the result inside $add variable. Print the $add variable using echo statement. Do the same for sub( ) method and store the result in $sub variable. Now create the object of demo class, using «new» keyword and store the object reference in $obj variable. call the method add( ) and sub( ) with the help of object(using connector(->) ).

Access current class methods inside other method

first + $this->second; echo "Addition=".$add."
"; > function sub( ) < $sub=$this->first - $this->second; echo "Subtraction=".$sub."
"; > function summary() < $this->add( ); $this->sub( ); $res=$this->first*$this->second; echo "Multiplication=".$res; > > $obj= new demo(); $obj->summary(); ?>

In the above example Create a class demo with two properties $first and $second, three methods add( ), subtract( ) and summary( ). Use the current class property $first and $second, inside add( ) and sub( ) method make calculation and store the result inside $add and $sub variable. Now Inside summary( ) method call the current class property $first and $second for multiplication, and print the result with the help of echo statement. Inside summary( ) method, call current class add( ) and sub( ) method using $this. after closing of class demo body, create object of demo class and store the object reference in $obj variable. call summary( ) method, with the help of connecter(connect class object with class method) and output will display addition, subtraction, and multiplication.

Источник

Оцените статью