Jump to content

Please explain "->" and "$this"


makenoiz

Recommended Posts

Hi Everyone

 

I have tried to find tutorials to explain the following code and I cant get any search results. Can anyone tell me what the following code means? Im having problems with the "->"

 

$ret = $this->variableB->functionC();

 

Thank you

 

Makenoize

 

Although I've honestly never seen a class of a class, I can explain using this example:

 

 

ClassA.php

<?php

class Echo
{

var $username;
var $saying;

function dosomething()
{
	echo "$this->username: $this->saying";
}

function dosomethingelse($username,$saying)
{
	echo "$username: $saying";
}
}

?>

 

Example.php

<?php
include 'ClassA.php';

$output = new Echo;
$output_else = new Echo;

//First function

$output->username = "Bob";
$output->saying = "I love using Object Oriented Programming!";
$output->dosomething();//outputs "Bob: I love using Object Oriented Programming!"

//Second function

$output->dosomethingelse("Bob","I love using Object Oriented Programming!");
//outputs "Bob: I love using Object Oriented Programming!"

?>

 

When you want to call other variables in a class, we use the $this->variable in order to do things with it (only inside a class). You can do anything with it, retrieve value, store value, string, array, etc... You can also call another function inside the same class by going $this->function();

 

If you are outside of the class, as in a php file that includes the class, you have to create a new variable that defines the class (IE: $output = new Echo;) Then, you can call variables from that class by going $output->variable. Similarly, $output->function();

 

Any questions about this?

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.