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
Share on other sites

$this is a reserved variable name that points to an object from within itself - that is, an object can access its own variable MyVar by using $this->Myvar.  the arrow (->) accesses the various methods and properties of an object.

Link to comment
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.