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?

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.