Forum Moderators: coopster

Message Too Old, No Replies

$this->addr

         

Gruessle

12:10 am on Apr 28, 2005 (gmt 0)

10+ Year Member




I am looking at someelses script and don't understand what this $this-> does?
I mean $addr is the veriable and then what is this $this->addr good for?

$this->addr=$addr;
$this->addr

ironik

12:21 am on Apr 28, 2005 (gmt 0)

10+ Year Member



$this-> is a reference to an objects internal properties and methods. In PHP objects can store data and hold functions (methods).

E.g:

class MyClass {
var $myVar = 'some contents';
function myFunction ()
{
return $this->myVar;
}
}

You instantiate the object and use it like this:
$myObject = new MyClass;
$getVar = $myObject->myFunction();
print $getVar; // Outputs 'some contents'

You can read more about it in the PHP manual:
[php.net...]

Be aware that there are some major enhancements to objects in PHP5.

Gruessle

5:02 am on Apr 28, 2005 (gmt 0)

10+ Year Member



I am starting to understand I think

this is an example from php.net
class Cart {
var $todays_date;
var $name;
var $owner;
var $items = array("VCR", "TV");

function Cart() {
$this->todays_date = date("Y-m-d");
$this->name = $GLOBALS['firstname'];
/* etc. . . */
}
}

Now I with my mind would do this like this:
class Cart {

function Cart() {
$todays_date = date("Y-m-d");
$name = $GLOBALS['firstname'];
/* etc. . . */
}
}

So I still not understand what that "this->" is.

Also when I call this I have to do :
$cart = new Cart;
$cart->add_item("10", 1);

Now what is that new is there an old too?

I would have just called it:
$cart = Cart(add_item("10", 1));

grandpa

5:58 am on Apr 28, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



this-> is a reserved PHP variable, also called a pseudo-variable.

In order to be able to access it's own functions and variables from within a class, one can use the pseudo-variable $this which can be read as 'my own' or 'current object'. reference [us4.php.net]

This variable is used in Object Oriented Programming and relates to classes and inheritence.


class MyClass {
var $myVar = 'some contents';
function myFunction ()
{
return $this->myVar;
}
}

You instantiate the object and use it like this:
$myObject = new MyClass;
$getVar = $myObject->myFunction();
print $getVar; // Outputs 'some contents'

"return $this->myVar" is interpreted as, "return of the value of myVar as it exists in this class." The value of "this->" will become more apparent as your understanding of classes and OOP increases.

dreamcatcher

8:49 am on Apr 28, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



For more info check here:

http://us2.php.net/oop [us2.php.net]

[edit]Oops, just saw ironik already posted the link. :)