Jump to content

$this-> Don't understand


aim25

Recommended Posts

Hi, a few days ago i started reading about oop in php. So i thought id give it a try. Ive gone through all the basic syntax's and scopes and magic methods and all, but one thing i can't get is the "$this" and the "->". Could some one give me an easy laymans definition please.

 

Any help is appreciated, thanks ahead of time. :)

Link to comment
https://forums.phpfreaks.com/topic/65101-this-dont-understand/
Share on other sites

To expand on what was explained before:

 

When using $this-> within a class definition for OOP, you are telling the system to reference the specific instance of a class rather than the actual function itself. For instance:

 

<?php

class Bar { 
   var $text;

   function HelloWorld() {
          echo $this->text;
    }
}

$Foo = new Bar;
$Foo->text = "Hello, World! <br>";
$Foo2 = new Bar;
$Foo2->text = "Goodbye, World! <br>";
$Foo->HelloWorld();
$Foo2->HelloWorld();
?>

 

In the code above, we created two instances of the same class. When we called the HelloWorld() function for each class, the $this->text keyword replaced "$this" with the corresponding class name ($Foo and $Foo2).

Link to comment
https://forums.phpfreaks.com/topic/65101-this-dont-understand/#findComment-324977
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.