K
K
Keymorfist2016-11-28 22:10:28
PHP
Keymorfist, 2016-11-28 22:10:28

Am I understanding the $this parameter correctly?

Good afternoon/evening. I started learning PHP and OOP ran into a misunderstanding of myself. It seems that I understand and do not understand the $this variable.
Please see the simple code and tell me if I understand the $this parameter correctly?

class worker {
    
    //Устанавливаем значения переменных по умолчанию
    public $name        = "Имя и Фамилия";
    public $balance     = "Баланс";
    public $savings     = "Зарплата";
    public $profession  = "Профессия";
    public $income      = "Доход";
    public $despense    = "Расход";
    
    /*Создаем конструкцию для объекта*/
    
    //В конструкцию устанавливаем параметры, которые нужно изменить при обращении к методу
    function __construct ($name, $balance, $savings, $profession, $income, $despense) {
        
        //Обращаемся к переменной $name и присваиваем стандартное значение из класса worker
        $this->name         = $name;
        $this->balance      = $balance;
        $this->savings      = $savings;
        $this->profession   = $profession;
        $this->income       = $income;
        $this->despense     = $despense;
    }
}

/*Создаем переменную $worker2 и присваиваем ему объект worker
 *Указываем данные для параметров*/
$worker2 = new worker("Призрак", 5000, 535000, "Спецагент ЦРУ", 44223493, 20330);

//Вывод данных 
echo "Имя: ".$worker2->name."<br>";
echo "Баланс: ".$worker2->balance." руб.<br>";
echo "Зарплата: ".$worker2->savings." руб.<br>";
echo "Профессия: ".$worker2->profession."<br>";
echo "Доход: ".$worker2->income." руб.<br>";
echo "Расход: ".$worker2->despense." руб.<br>";

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Entelis, 2016-11-28
@Keymorfist

$this points to the current instance of the class.
The code $this->name = $name;sets the name parameter of the current object instance to $name.
Visually, the code looks correct, except that it’s better to immediately get used to calling a spade a spade - __construct is a constructor and not a construct)
Well, just in case php.net/manual/en/language.oop5.basic.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question