Using this in php class

PHP self Vs this

In PHP, the self and this keyword are used to refer to class members within the scope of a class. The class members can be either variables or functions. These PHP keywords differ from the static behavior of the class members.

PHP this keyword refers to a non-static member of a class with respect to the class instance created. So, the values or arguments of the class members will be varied based on the value with which the instance of the class is created.

If we use this keyword without object context for referring to static data, then the following error will be displayed to the browser.

Fatal error: Using $this when not in object context in . on Line 

So, we should use the self keyword in such places to refer to static members of the class to avoid the above error. While using self for referring to static data, we need to use the scope resolution operator. For example,

In the above code sample, we have shown how the static variable $menu is referred PHP self-keyword.

Difference between the PHP self and this

self this
the self-keyword will not be preceded by any symbol; rather we can use it as it is. But PHP this keyword should be preceded with a $ sign while referring class members.
PHP scope resolution operator will be used with the self keyword. For example, self:: -> symbol is used with $this variable as we have used with an object instance to access the property of that object. For example, $this->
It will be used for referring to a static member of a class. this is used for accessing non-static members with -> operator.
PHP self is referring to class members, not for any particular instance; rather, all of the class instances will use the same static member by the use of self. But, $this will refer class members for a particular instance of the class.

Example: PHP self Vs this

Let us see the above differences with a simple PHP program as an example to know, how the class members are referred to these two PHP keywords.

toys_name = $name; $this->toys_category = $category; > public function getToyName() < return $this->toys_name; > public function getToyCategory() < return $this->toys_category; > public function getToyShop_nonStatic() < return self::getToyShop(); >public static function getToyShop() < return self::$shop_name; >public static function setToyShop($shopname) < self::$shop_name = $shopname; >> $objToys = new Toys("Battery Car", "Battery Toys"); $toys_name = $objToys->getToyName(); $toys_category = $objToys->getToyCategory(); echo "
Toy: " . $toys_name . ", Category: " . $toys_category; Toys::$shop_name = "Disney"; $shop_name = Toys::getToyShop(); echo "
Shop Name: " . $shop_name; Toys::setToyShop("ToyShop"); $shopname = Toys::getToyShop_nonStatic(); echo "
Shop Name via non static function: " . $shopname; ?>

In the above program, we have three member variables for the Toys class. Two of those are non-static, expected to be initialized automatically while creating class instances. And, the class contains only one static variable commonly referred to for all instances of the class.

With constructors, the class variables are referred to by using $this, for initialization. Again, using $this variable the initialized members variables are referred to for class getters defined as a non-static member function, returning required values for a particular class instance.

On the other hand, static members are referred to as a self keyword to return the static value of $shop_name by the static member function getToyShop() of the Toys class.

Outside the class, first, we have created an instance with two arguments, for automatically calling the class constructor. With respect to this object or instance, the non-static member functions are invoked to get the value of $toys_name and $toys_category. Now, member functions use $this to refer to those values initialized on instantiation.

And then, the static members are accessed from outside the class by using the class name itself. But, within class scope, we have used self to access those members. In this program, we have retrieved static variable values by using non-static member function getToyShop_nonStatic(), also.

After executing the above PHP program, it will return the following output to the browser to be displayed.

Toy: Battery Car, Category: Battery Toys Shop Name: Disney Shop Name via non static function: ToyShop 

Источник

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.

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 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.

Источник

Читайте также:  Xmltodict python 3 install
Оцените статью