...

View Full Version : the difference between $this->$var and $this->var



Exodious
11-21-2003, 12:50 AM
class sample
{
var $tempvar1;
var $tempvar2;
function sample()
{
$this->$tempvar1 = "hi";
$this->tempvar2 = "hi";
}

}


Hiya, simple stuff, what is the difference between the two above assignments?

I'm guessing or feeling that $this->tempvar2 is a reference to the variable/properties of tempvar2, and $this->tempvar1 is a ref to the actual object it contains (if it were an object)

Am i close?

missing-score
11-21-2003, 01:17 AM
i dont know that

$this->$varname

is even meant to be used.

Exodious
11-21-2003, 03:15 PM
Does that mean it $this->$var should never be used?

I can assign a variable value to it and print it out etc... created dblink to mysql then closed it, seems to work ok, if its never meant to be used, then why does it work? It must have some purpose?

Just trying to clear up a few things about php so I know for certain what is, what can, and what isnt.

Thx

missing-score
11-21-2003, 03:28 PM
some things in php work, even though they shouldnt.

eg:



<?php

echo hi;

?>


will actually print hi, even though it is not a string.

I used this example:




class classname {

var $var;

function set(){

$this->$var = "Hello";

}

function get(){

return $this->$var;

}

}

$class = new classname();

$class->set();

echo $class->get();



prints Hello.

however, i test on my local server, and have error reporting set to E_ALL, meaning it will display every tiny error it finds.

both the:

echo hi;

example, and the class refrencing $this->$var give errors.

My output from "echo hi;" was:


Notice: Use of undefined constant hi - assumed 'hi' in C:\apache\www\TMPbbxlbophfo.php on line 3
hi



and from the class:


Notice: Undefined variable: var in C:\apache\www\TMPbdde7ophhj.php on line 9

Notice: Undefined variable: var in C:\apache\www\TMPbdde7ophhj.php on line 15
Hello



so referencing variables in a class should not be done $this->$var at all.

firepages
11-21-2003, 07:27 PM
... unless its intentional eg as a dynamic method/function/property call , eg I do this quite a lot ... (class_exists() is a useful function to be using here)



<?
class whatever{
function method_farm( $method , $array_data ){
$this->$method( $array_data ) ;
}
}
?>


so its valid if intentional ;)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum