- PHP $this Keyword
- Using self for static Class Members
- Difference between PHP self and this
- PHP $this
- What is $this in PHP?
- Chaining methods
- Summary
- PHP RFC: Fix inconsistent behavior of $this variable
- Proposal
- Disable using $this as parameter
- Disable using $this as static variable
- Disable using $this as global variable
- Disable using $this as catch variable
- Disable using $this as foreach value variable
- Disable ability to unset() $this
- Disable ability to re-assign $this indirectly through $$
- Disable ability to re-assign $this indirectly through reference
- Disable ability to re-assign $this indirectly through extract() and parse_str()
- get_defined_vars() always doesn’t show value of variable $this
- Always show true $this value in magic method __call()
- Using $this when not in object context
- Backward Incompatible Changes
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.
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.
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->balance
Code 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 RFC: Fix inconsistent behavior of $this variable
Historically PHP implementation accessed special $this variable using two different methods. In some cases this might lead to significant inconsistency, when $this accessed through different methods might have different values.
class C { function foo() { var_dump($this); } function bar() { $a="this"; $$a=42; var_dump($this); // prints int(42) $this->foo(); // prints object(C)#1 (0) <> } } $x = new C; $x->bar();
This RFC proposes disabling modification of $this variable using “magic code” and make $this always behave in the same way.
Proposal
Disable using $this as parameter
The following code worked in PHP 7, but will emit compilation error in PHP 7.1
function foo($this) { // Fatal error: Cannot use $this as parameter }
Disable using $this as static variable
The following code leaded to “Cannot re-assign $this” compilation error. In PHP 7.1 it will produce more suitable error message — “Cannot use $this as static variable”.
static $this; // Fatal error: Cannot use $this as static variable
Disable using $this as global variable
The following code worked in PHP 7, but will emit compilation error in PHP 7.1
global $this; // Fatal error: Cannot use $this as global variable
Disable using $this as catch variable
The following code worked in PHP 7, but will emit compilation error in PHP 7.1
try { . } catch (Exception $this) { // Fatal error: Cannot re-assign $this }
Disable using $this as foreach value variable
The following code worked in PHP 7, but will emit compilation error in PHP 7.1
foreach ($a as $this) { // Fatal error: Cannot re-assign $this }
Disable ability to unset() $this
It’s not allowed to re-assign $this, so why it should be allowed to unset() it. The following code worked in PHP 7, but will emit compilation error in PHP 7.1
unset($this); // Fatal error: Cannot unset $this
Disable ability to re-assign $this indirectly through $$
An attempt to re-assign $this through $$ assignment will lead to throwing of Error exception.
$a = "this"; $$a = 42; // throw new Error("Cannot re-assign $this")
It’s still possible to read $this value through $$.
Disable ability to re-assign $this indirectly through reference
Indirect re-assign $this through reference won’t make effect in PHP 7.1
class C { function foo(){ $a =& $this; $a = 42; var_dump($this); // prints object(C)#1 (0) <>, php-7.0 printed int(42) } } $x = new C; $x->foo();
Disable ability to re-assign $this indirectly through extract() and parse_str()
Few internal PHP functions may re-assign local variable. In PHP 7.1 they cannot change value of $this variable and throw Error exception.
class C { function foo(){ extract(["this"=>42]); // throw new Error("Cannot re-assign $this") var_dump($this); } } $x = new C; $x->foo();
get_defined_vars() always doesn’t show value of variable $this
In PHP 7.0 and below get_defined_vars() might show or not show value of $this depending on some condition. (e.g. it was shown if we used $this variable itself, but not if it was used in a $this property reference or method call). In PHP 7.1 we won’t show the value of $this in all cases.
Always show true $this value in magic method __call()
In PHP 7.0 and below $this in static magic method __call() had value NULL. However it was possible to access properties and call object methods.
class C { static function __call($name, $args) { var_dump($this); // prints object(C)#1 (0) <>, php-7.0 printed NULL $this->test(); // prints "ops" } function test() { echo "ops\n"; } } $x = new C; $x->foo();
Using $this when not in object context
Attempt to use $this in plain function or method now will lead to exception “Using $this when not in object context”. This unifies behavior with method call and property access. Previously PHP emitted “undefined variable” notice and continued execution assuming $this is NULL. It’s still possible to use isset($this) and empty($this) to check object context.
function foo() { var_dump($this); // throws "Using $this when not in object context" // php-7.0 emitted "Undefined variable: this" and printed NULL } foo();
Backward Incompatible Changes
All the BC breaks are intentional and they are described in the proposal section.