-2

So, I tried learning PHP and I don't understand the use of $this keyword. I know that it is a pre-defined keyword and it is in-built reference to class. But what does it mean here.

<!DOCTYPE html>
<html>
<body>

<?php
class Fruit {
  public $name;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}

$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
echo $apple->get_name();
?>
 
</body>
</html>

specifically here
function set_name($name) { $this->name = $name; }
and
function get_name() { return $this->name; }
can't we just store the name in $name then just use it to return the name in get_name method

jaydeva
  • 11
  • 2
  • 2
    Does this answer your question? [What does the variable $this mean in PHP?](https://stackoverflow.com/questions/1523479/what-does-the-variable-this-mean-in-php)... almost the same title. – Syscall Jan 18 '22 at 11:49
  • @Syscall yeah, thank you – jaydeva Jan 18 '22 at 12:21

2 Answers2

0

$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.

0

PHP variables only can be accessed or modified inside a scope like this in PHP.

$this->.. is similar to using the sentence: global $name; inside a function before using it; or the variable $GLOBALS["name"].


ferran
  • 100
  • 2
  • 8