This member php u

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,

Читайте также:  Label html блочный или строчный

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.

Источник

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

Источник

ЗлостныйКодер

У каждого обычно возникает вопрос, что такое $this, что такое self, для чего они используются и в чем разница между ними?
ПРАВИЛА КОТОРЫЕ ВЫ ДОЛЖНЫ ЗАПОМНИТЬ:

  1. Статические функции должны использовать только статические переменные.
  2. self ТОЛЬКО для статических функций, свойств. Но также можно вызвать нестатический метод, КАК СТАТИЧЕСКИЙ через self. Но лучше так не делать, а то папа побьет.
  3. this ТОЛЬКО для нестатических.
  4. 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; //обращение к name
echo $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() ;

Источник

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