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.
ЗлостныйКодер
У каждого обычно возникает вопрос, что такое $this, что такое self, для чего они используются и в чем разница между ними?
ПРАВИЛА КОТОРЫЕ ВЫ ДОЛЖНЫ ЗАПОМНИТЬ:
- Статические функции должны использовать только статические переменные.
- self ТОЛЬКО для статических функций, свойств. Но также можно вызвать нестатический метод, КАК СТАТИЧЕСКИЙ через self. Но лучше так не делать, а то папа побьет.
- this ТОЛЬКО для нестатических.
- this требует, чтобы класс был проинстанцирован, self не требует.
public function klassFunc() <>; function getName() echo $name; // неправильно, обратиться не к переменной public name echo $this->name; // правильно //вызов метода класса $this->klassFunc(); > >
Обычна нужна, чтобы инициализировать поля в конструкторе, ну и не только:
public function __construct($name)$name = $name; //будет ошибка$self используется в том, же самом ключе, но уже для СТАТИЧЕСКИХ свойств:
class human static $name = "ololo";public function klassFunc() <>; function getName() echo self::$name; //обращение к nameecho $this->name; //null или ошибка. НЕЛЬЗЯ > >Проверочная программа которая показывает главную разницу между self и $this:
class Klass const STAT = 'S' ; // константы всегда статичны static $stat = 'Static' ;
public $publ = 'Public' ;
private $priv = 'Private' ;
protected $prot = 'Protected' ;public function show ( ) print '
self::STAT: ' . self :: STAT ; // ссылается на константу
print '
self::$stat: ' . self :: $stat ; // статическая переменная.
print '
$this->stat: ' . $this -> stat ; // Ошибки нет, но выведет пустую строку. ПРЕДУПРЕЖДЕНИЕ.
print '
$this->publ: ' . $this -> publ ; // выведет как надо
print '
' ;
>
> $me = new Klass () ; $me -> show () ;Результат:
self::STAT: S
self::$stat: Static
Strict Standards: Accessing static property Klass::$stat as non static in htdocs\test\testReference.php on line ..
Notice: Undefined property: Klass::$stat in C:\xampp\htdocs\test\testReference.php on line 50
$this->stat:
$this->publ: Public
Видно, что php умный и кидает предупреждения глупым программистам. Не делайте так.Второе главное отличие состоит в том, что
self не использует таблицу виртуальных методов, то есть:
(взято с StackOverflow)class Person private $name; public function __construct($name) $this->name = $name; > public function getName() return $this->name; > public function getTitle() return $this->getName()." the person"; > public function sayHello() echo "Hello, I'm ".$this->getTitle()."
"; > public function sayGoodbye() echo "Goodbye from ".self::getTitle()."
"; > > class Geek extends Person public function __construct($name) parent::__construct($name); > public function getTitle() return $this->getName()." the geek"; > > $geekObj = new Geek("Ludwig"); $geekObj->sayHello(); $geekObj->sayGoodbye();Hello, I'm Ludwig the geek
Goodbye from Ludwig the personПояснение:
Метод sayHello использует this, поэтому виртуальная таблица вызовет Geek::getTitle()
Метод sayGoodbye использует self, поэтому виртуальная таблица будет не задействована и будет вызван parent::getTitle()Решение:
Используем вместо self, static keyword:
public function sayGoodbye() echo "Goodbye from ". static::getTitle() ;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.
Public, private и $this в ООП на PHP
Внутри классов, перед методами и свойствами, можно встретить слова public, private. Разберёмся для чего они нужны. А также посмотрим как обратиться к методу или свойству изнутри класса.
Переменная $this внутри класса
На реальных проектах сайтов используется множество классов. И часто возникает необходимость обратиться к свойству или методу класса изнутри его самого. Конечно, можно написать "new . " и создать новый объект класса внутри класса, но зачем это делать, если мы уже в этом классе? Есть ругой выход - специальная переменная $this , которая работает внутри классов. Продемонстрируем способ её применения на примере получения значения свойства:
string; > > $a = new Mouse; $b = $a->Name(); echo $b; ?>
В результате выполнения этого кода будет распечатано слово "Мышь".
Как можно догадаться, через $this можно обратиться не только к свойству, как в приведённом примере, так и к методу внутри класса. Продемонстрируем это:
public function Description()< return $this->Name(); > > $a = new Mouse; $b = $a->Description(); echo $b; ?>
Модификаторы доступа (public, private)
Внутри классов можно встретить слова public и private - это модификаторы доступа. Они нужны для того, чтобы блокировать или разрешить доступ к методу или свойству извне. То есть если установить "private", то будет доступ только изнутри класса, с помощью $this. При этом нельзя будет вызывать метод или свойство за пределами класса. Продемонстрируем это на примере:
> $a = new Mouse; $b = $a->Name(); echo $b; ?>
[Error] Call to private method Mouse::Name() from context ''
Name(); > private function Name() < return 'Мышь'; >> $a = new Mouse; $b = $a->Description(); echo $b; ?>
Посмотрите внимательно на пример: у функции "Name()" всё так же остался модификатор доступа "private", который не даёт обратиться к методу извне. Но код успешно выполнится, потому что обращение к "Name()" идёт через функцию "Description()", в которой стоит "$this->Name();".
Модификаторы public и private нужны для того, чтобы запретить доступ к тем методам и свойствам, которые не должны быть публичными. К примеру, представьте что есть свойство, которое возвращает пароль доступа к системе. Очевидно, что если программист доспустит ошибку, то эта секретная информация может стать публичной. Поэтому лучше задать ей модификатор "private".
Правилом хорошего тона программирование является использование "private" для новых методов и свойств. А если в процессе разработки потребуется сделать запрос к ним извне класса, то "private" меняется на "public". Но изначально лучше везде ставить "private".